reduce
Boil an array down to a single value.
Syntax
arr.reduce((acc, item) => ..., start)reduce() combines all items into a single value, such as a sum or a total.
How it works
The callback receives an accumulator (the running result) and the current item. Whatever you return becomes the accumulator for the next item. The second argument to reduce is the starting value.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Sum all line-item totals in an order array to produce a single cart grand total.
- Group an array of transactions by their category property into a categorised summary object.
- Flatten an array of arrays into a single flat array using reduce and spread.
More examples
Sum an array of numbers
Accumulates a running sum starting from 0 and ending with the cart total.
const prices = [19.99, 5.49, 12.00];
const total = prices.reduce((acc, price) => acc + price, 0);
console.log(total.toFixed(2)); // "37.48"Group by property
Builds an object that groups transaction amounts by category using reduce.
const txns = [
{ cat: "food", amount: 12 },
{ cat: "travel", amount: 50 },
{ cat: "food", amount: 8 }
];
const grouped = txns.reduce((acc, t) => {
acc[t.cat] = (acc[t.cat] ?? 0) + t.amount;
return acc;
}, {});
console.log(grouped); // { food: 20, travel: 50 }Flatten nested arrays
Concatenates each sub-array into the accumulator to flatten one level of nesting.
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], []);
console.log(flat); // [1, 2, 3, 4, 5]
Discussion