Sub topic 10
Combining Elements into One Value with reduce
This chapter assumes you already know how array callbacks receive (element, index, array) and how map and filter return new arrays. reduce works differently. It walks the array and folds every element into a single result. That result can be a number, a string, an object, or even another array.
The working model
reduce takes two arguments: a reducer callback and an optional initial value.
array.reduce((accumulator, element, index, array) => newAccumulator, initialValue);The accumulator holds the result built so far. On each step, reduce calls your callback with the current accumulator and the next element. Whatever the callback returns becomes the accumulator for the next step. After the last element, reduce returns the final accumulator.
const prices = [3, 5, 2];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 10Building objects and other shapes
The accumulator does not have to be a number. A common use is counting or grouping items into an object:
const votes = ['yes', 'no', 'yes', 'yes', 'abstain'];
const tally = votes.reduce((counts, vote) => {
counts[vote] = (counts[vote] ?? 0) + 1;
return counts;
}, {});
console.log(tally); // { yes: 3, no: 1, abstain: 1 }You can also find a maximum by keeping the best element seen so far:
const scores = [{ name: 'Ana', points: 12 }, { name: 'Ben', points: 30 }, { name: 'Cleo', points: 21 }];
const best = scores.reduce((top, s) => (s.points > top.points ? s : top));
console.log(best.name); // 'Ben'This version leaves out the initial value. Without one, reduce uses the first element as the starting accumulator and begins at the second element. That works here because the accumulator and the elements have the same shape.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `return` in a block-body callback | Accumulator becomes `undefined` after the first step | Always return the accumulator |
| Omitting the initial value when building an object or a sum of properties | The first element is used as the accumulator, so you get wrong types such as `"[object Object]20"` | Pass `{}`, `0`, or `[]` explicitly |
| Calling `reduce` on an empty array without an initial value | `TypeError: Reduce of empty array with no initial value` | Supply an initial value |
| Using `reduce` where `map` or `filter` fits | Code that is hard to read | Use the more specific method |
Exercises
Exercise
Use reduce to turn ['a', 'bb', 'ccc'] into an object mapping each string to its length, giving { a: 1, bb: 2, ccc: 3 }.
Show answer
['a', 'bb', 'ccc'].reduce((acc, s) => { acc[s] = s.length; return acc; }, {}); The initial value {} is required. Without it, the accumulator would start as the string 'a'.
Exercise
What does [{ n: 4 }, { n: 6 }].reduce((sum, item) => sum + item.n) return, and why?
Show answer
It returns '[object Object]6'. With no initial value, sum starts as the first object { n: 4 }. Adding 6 to that object converts it to a string. Passing 0 as the initial value gives 10.