Dev Helpers
← Back

Pivot readings into an hourly site matrix

Pivot readings into an hourly site matrix. Build the result in an App Router server page and send the rendered entries to the client.

Open this example in the interactive library

Source code

// app/pivot-readings-into-an-hourly-site-matrix/page.tsx
export const metadata = { title: "Pivot readings into an hourly site matrix" };
export default function Page() {
  const rows = [
    { site: "N", hour: 8, value: 12 },
    { site: "S", hour: 8, value: 17 },
    { site: "N", hour: 9, value: 15 },
    { site: "S", hour: 9, value: 14 },
  ];
  const result = Object.fromEntries(
    [...new Set(rows.map((r) => r.hour))].map((h) => [
      h,
      Object.fromEntries(
        rows.filter((r) => r.hour === h).map((r) => [r.site, r.value]),
      ),
    ]),
  );
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Pivot readings into an hourly site matrix"}</h2>
      {entries.length ? (
        <dl>
          {entries.map(([key, value]) => (
            <div key={key}>
              <dt>{key}</dt>
              <dd>
                {typeof value === "string" ? value : JSON.stringify(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p>No matching entries.</p>
      )}
    </section>
  );
}