Aggregating Arrays with .reduce()
Quick Overview
`.reduce()` carries an accumulator across the array, and the initial value decides the shape of the result: `0` gives a number, `{}` an object, `[]` an array. Omit it and the first element becomes the seed.
Deep Dive
1. Condensing an Array
The .reduce() method executes a user-supplied "reducer" callback function on each element of the array, passing in the return value from the calculation on the preceding element.
2. Why It Matters
.reduce() is the swiss army knife of array methods. It can compute total sums, flatten nested arrays, or build complex objects from array streams in a single pass.
3. The Reducer Pattern
Pass a callback function taking (accumulator, currentValue) and an explicit initial accumulator starting value:
const cartPrices = [15, 25, 10];
// Sum total prices with initial accumulator 0
const totalCost = cartPrices.reduce((sum, price) => {
return sum + price;
}, 0);
console.log(totalCost); // 50
4. Building Objects with .reduce()
You can use .reduce() with an empty object {} initial value to count occurrences or group items:
const votes = ["yes", "no", "yes", "yes", "no"];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc; // Must return the updated accumulator!
}, {});
console.log(tally); // { yes: 3, no: 2 }
5. Common Mistakes
- Omitting the Initial Accumulator Value: If you omit the initial value argument in
.reduce(), array element 0 becomes the initial accumulator and iteration starts at index 1. On empty arrays, omitting the initial value throws an uncaughtTypeError: Reduce of empty array with no initial value! - Forgetting to Return Accumulator: The reducer function MUST return the updated accumulator at the end of every step.
6. Try It Yourself
Write it yourself. The tests below run against your code.
Sum Array Numbers with .reduce()
Examples
7. Next Steps
Always supply an initial accumulator value to .reduce(). Next, let's explore clean variable unpacking with Destructuring!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.