Dev Helpers
← Back

Total units for each SKU

Total units for each SKU. 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/total-units-for-each-sku/page.tsx
export const metadata = { title: "Total units for each SKU" };
export default function Page() {
  const rows = [
    { sku: "pen", bin: "A", qty: 4 },
    { sku: "pad", bin: "B", qty: 0 },
    { sku: "pen", bin: "B", qty: 3 },
    { sku: "clip", bin: "A", qty: 9 },
  ];
  const result = Object.fromEntries(
    [...new Set(rows.map((r) => r.sku))].map((sku) => [
      sku,
      rows.filter((r) => r.sku === sku).reduce((sum, r) => sum + r.qty, 0),
    ]),
  );
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Total units for each SKU"}</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>
  );
}