Hint
reduce is ideal for grouping and aggregating — a single pass over an array to build any shape of output.
const orders = [
{ cat: 'A', val: 10 },
{ cat: 'B', val: 20 },
{ cat: 'A', val: 30 },
];
const totals = orders.reduce((acc, o) => {
acc[o.cat] = (acc[o.cat] || 0) + o.val;
return acc;
}, {});
console.log(totals.A);
console.log(totals.B);40 20
Explanation: reduce builds a totals map. A: 10+30=40. B: 20.
Key Insight: reduce is ideal for grouping and aggregating — a single pass over an array to build any shape of output.