reduce
reduce turns a whole array into one value, which makes it the most general of the array methods and the one worth learning last.
reduce carries an accumulator from item to item, and whatever the callback returns becomes the accumulator for the next one. Always supply a starting value. Every other array method can be written with it.
EXERCISE
1Carrying a Value Through the Array
reduce keeps a running value as it walks the array, handing it to your callback each time along with the current item.
The shape, with the simplest possible job:
const numbers = [1, 2, 3, 4];
const total = numbers.reduce((sum, n) => sum + n, 0);
// ^acc ^item ^starting value
console.log(total); // 10
Watching it run:
const numbers = [1, 2, 3, 4];
numbers.reduce((sum, n) => {
console.log(`sum is ${sum}, item is ${n}`);
return sum + n;
}, 0);
// sum is 0, item is 1 -> returns 1
// sum is 1, item is 2 -> returns 3
// sum is 3, item is 3 -> returns 6
// sum is 6, item is 4 -> returns 10
Whatever the callback returns becomes the sum for the next turn. The last return is the answer.
Compare with the loop it replaces:
const numbers = [1, 2, 3, 4];
let total = 0;
for (const n of numbers) {
total = total + n;
}
console.log(total); // 10
// reduce is that pattern with the `let` and the loop built in.
Summing a field from a list of objects:
const cart = [
{ name: "Tea", price: 40, qty: 2 },
{ name: "Coffee", price: 120, qty: 1 },
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
console.log(total); // 200
The two parameters are always in the same order: the value you are building first, the current item second. Naming the first one for what it is, sum, total, counts, rather than the generic acc, makes a reduce far easier to read back, because the name then tells you what is being built.
EXERCISE
2Always Supply a Starting Value
The second argument to reduce is optional, and leaving it out changes the behaviour in ways that cause real bugs.
With a starting value, the callback runs once per item:
const numbers = [1, 2, 3];
console.log(numbers.reduce((sum, n) => sum + n, 0)); // 6
// sum starts at 0, and all three items are visited.
Without one, the first item becomes the starting value:
console.log(numbers.reduce((sum, n) => sum + n)); // 6
// sum starts at 1, and only items 2 and 3 are visited.
// Same answer here. Not always.
Where it goes wrong, case one: the empty array:
const empty = [];
console.log(empty.reduce((sum, n) => sum + n, 0)); // 0
console.log(empty.reduce((sum, n) => sum + n));
// TypeError: Reduce of empty array with no initial value
Where it goes wrong, case two: building a different type:
const words = ["a", "b", "c"];
// Building an object, with a starting value:
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] ?? 0) + 1;
return acc;
}, {});
console.log(counts); // { a: 1, b: 1, c: 1 }
// Without the {}, the first STRING becomes the accumulator:
// words.reduce((acc, word) => { acc[word] = 1; return acc; });
// acc is "a", a string, and writing a property to it silently fails.
The rule:
// Sum of numbers -> start at 0
// Product of numbers -> start at 1
// Building a string -> start at ""
// Building an array -> start at []
// Building an object -> start at {}
Pro Tip: Supply the starting value every single time, even when the answer would be the same without it. It costs three characters, it makes the type of the result obvious to anyone reading the line, and it removes both the empty-array crash and the silent wrong-type bug in one go.
EXERCISE
3What reduce Is Good For, and When Not to Use It
reduce can express every other array method, and that power is exactly why it can also produce code nobody wants to read.
Jobs where reduce is the right answer:
const cart = [
{ name: "Tea", price: 40, qty: 2 },
{ name: "Coffee", price: 120, qty: 1 },
];
// A single total from many items:
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
console.log(total); // 200
// Grouping into an object:
const people = [
{ name: "Ada", city: "London" },
{ name: "Grace", city: "New York" },
{ name: "Alan", city: "London" },
];
const byCity = people.reduce((acc, person) => {
acc[person.city] = acc[person.city] ?? [];
acc[person.city].push(person.name);
return acc;
}, {});
console.log(byCity);
// { London: [ 'Ada', 'Alan' ], 'New York': [ 'Grace' ] }
Jobs where reduce is the wrong answer:
const numbers = [1, 2, 3, 4];
// Doubling: this is map, wearing a disguise.
const doubled = numbers.reduce((acc, n) => {
acc.push(n * 2);
return acc;
}, []);
const doubledBetter = numbers.map((n) => n * 2); // say what you mean
// Keeping evens: this is filter.
const evens = numbers.reduce((acc, n) => {
if (n % 2 === 0) acc.push(n);
return acc;
}, []);
const evensBetter = numbers.filter((n) => n % 2 === 0);
Finding a maximum, where reduce genuinely fits:
const users = [
{ name: "Ada", age: 36 },
{ name: "Grace", age: 45 },
];
const oldest = users.reduce((best, user) => (user.age > best.age ? user : best));
console.log(oldest.name); // Grace
Pro Tip: Use
reducewhen many items become one thing that is not simply a filtered or transformed list: a total, a maximum, a grouped object, a single joined string. If the result is an array of the same items reshaped,mapandfiltersay it better, and the person reading your code in six months will thank you for choosing the specific tool over the general one.
