reduce
Combine into one.
Add up a list of prices. Find the biggest number. Count how many times each word appears. Each of these combines a whole array into one value. That's what reduce does.

- Add up, find the biggest, count
- Many values into one
- reduce
An accumulator
Reduce takes a callback and a starting value. The callback gets the running result, called the accumulator, and the current item, and returns the new running result. Here we start at zero, and add each price. Then we use reduce to count fruit. Run it.
const prices = [4, 10, 6];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log("total:", total);
const basket = ["apple", "pear", "apple", "fig", "apple"];
const counts = basket.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(counts);total: 20
{ apple: 3, pear: 1, fig: 1 }Always give a start value
Always pass the starting value, the second argument to reduce. Without it, reduce uses the first item as the start, which breaks on empty arrays. Reduce is powerful, but it can be hard to read. For simple jobs, like a sum, it's perfect. For complicated ones, a loop can be clearer.
| key | value |
|---|---|
| reduce(fn, start) | combine into one |
| fn(acc, item) | returns the new acc |
| Start value | always pass it |
| Clear code | sometimes a loop is better |
Summary
Reduce combines an array into a single value, using an accumulator. Always give it a starting value. Next, chaining map, filter, and reduce.
Key takeaways- reduce((acc, x) => ..., start)
- Sums and counts
- Pass a start value