Dev Helpers
← Back

Find the weighted unit price by item

Find the weighted unit price by item. 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) => {
    const lines = rows.filter((r) => r.item === item);
    return [
      item,
      Math.round(
        lines.reduce((s, r) => s + r.units * r.cents, 0) /
          lines.reduce((s, r) => s + r.units, 0),
      ),
    ];
  }),
);
console.log(JSON.stringify(result, null, 2));

Sample output

{
  "tea": 335,
  "mug": 900,
  "tin": 500
}