Dev Helpers
← Back

Build a basket with consolidated quantities

Build a basket with consolidated quantities. Start with typed records and inspect the inferred result.

Open this example in the interactive library

Source code

type Row = { item: string; units: number; cents: number };
const rows: Row[] = [
  { item: "tea", units: 2, cents: 350 },
  { item: "mug", units: 1, cents: 900 },
  { item: "tea", units: 3, cents: 325 },
  { item: "tin", units: 2, cents: 500 },
];
const result = Object.fromEntries(
  [...new Set(rows.map((r) => r.item))].map((item) => [
    item,
    rows.filter((r) => r.item === item).reduce((n, r) => n + r.units, 0),
  ]),
);
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "tea": 5,
  "mug": 1,
  "tin": 2
}