Array Reduce Method
reduce() walks through an array and combines its elements into one value. It takes a callback and, usually, a starting value. The callback receives the result so far, called the accumulator, and the current element, and returns the new result so far. Whatever the last call returns is what reduce() returns.
const basket = [3.5, 12, 0.99, 6.25];
const total = basket.reduce((runningTotal, price) => { console.log(runningTotal, '+', price); return runningTotal + price;}, 0);
console.log('Total:', total);This prints:
0 + 3.53.5 + 1215.5 + 0.9916.49 + 6.25Total: 22.74The 0 after the callback is the starting value, so the first call receives 0 as the accumulator. The callback also receives the element’s index and the array as third and fourth arguments, as map() does.
Always give a starting value
Section titled “Always give a starting value”The starting value is optional. Without it, reduce() uses the first element as the accumulator and starts from the second. That works on a non-empty array, but an empty array then has nothing to start from, and reduce() throws a TypeError.
const empty = [];
console.log(empty.reduce((sum, n) => sum + n, 0));
try { empty.reduce((sum, n) => sum + n);} catch (error) { console.log(error.message);}This prints:
0Reduce of empty array with no initial valueGiving a starting value also makes the type of the result clear to the reader, because the result has the same type as the starting value.
Building an object
Section titled “Building an object”The accumulator can be any value, including an object. Here each book adds one to the count for its genre:
const books = [ { title: 'Emma', genre: 'novel' }, { title: 'The Waste Land', genre: 'poetry' }, { title: 'Middlemarch', genre: 'novel' }, { title: 'Ariel', genre: 'poetry' }, { title: 'Walden', genre: 'essay' },];
const countByGenre = books.reduce((counts, book) => { counts[book.genre] = (counts[book.genre] ?? 0) + 1; return counts;}, {});
console.log(countByGenre);This prints:
{ novel: 2, poetry: 2, essay: 1 }The callback must return the accumulator on every call, even when it has changed it in place. Forgetting the return makes the next call receive undefined. To put the elements themselves into groups rather than count them, Object.groupBy() does the job directly.
Picking one element
Section titled “Picking one element”reduce() can also choose an element by comparing each one with the best so far. Here no starting value is needed, because the array is known not to be empty and the first word is a fair first candidate:
const words = ['kettle', 'toaster', 'microwave', 'blender'];
const longest = words.reduce((best, word) => (word.length > best.length ? word : best));
console.log(longest);This prints:
microwaveFor a plain sum, a maximum or a minimum, a for...of loop or Math.max(...numbers) is often easier to read, so reach for reduce() when the combining step is the point. reduceRight() works the same way but goes from the last element to the first.
Steve Griffith covers this topic in his video JavaScript Array reduce method.