reduce: Boiling Down to One Value
reduce takes an entire array and combines everything into a single result: a number, an object, a string, anything.
The accumulator carries forward between iterations. The initial value sets the output shape (0 for sums, for objects, [] for arrays). reduce can replicate map and filter.
EXERCISE
1reduce() Combines Everything into One Result
While map returns an array and filter returns a subset, reduce takes an entire array and squashes it down into a single value: a number, a string, an object, anything.
reduce walks an array and combines everything into a single result. That result can be a number, a string, an object or another array. It is the most general of the three methods, and map and filter can both be written in terms of it.
const numbers = [5, 1, 3, 2, 6];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // 17
Two arguments, and the second is easy to miss because it sits outside the function. Read it first: 0 is the starting value of the accumulator.
Each call returns the new accumulator, and that return value arrives as accumulator on the next pass:
start: acc = 0
pass 1: acc = 0, current = 5 -> 5
pass 2: acc = 5, current = 1 -> 6
pass 3: acc = 6, current = 3 -> 9
pass 4: acc = 9, current = 2 -> 11
pass 5: acc = 11, current = 6 -> 17
Forgetting to return the accumulator is the mistake that produces the most confusing output:
const wrong = numbers.reduce((acc, n) => {
acc + n;
}, 0);
console.log(wrong); // undefined
The first pass returned undefined, which became the accumulator for the second pass, and so on. One missing return and the whole chain collapses.
Leaving out the initial value changes the behaviour:
console.log([5, 1, 3].reduce((a, b) => a + b)); // 9
console.log([].reduce((a, b) => a + b)); // TypeError: Reduce of empty array with no initial value
Without a starting value, the first element becomes the accumulator and iteration begins at the second. That works until the array is empty, at which point there is nothing to start from and it throws.
It also silently changes the result type when you are building something:
const nums = [1, 2, 3];
console.log(nums.reduce((acc, n) => acc + n, "")); // "123"
console.log(nums.reduce((acc, n) => acc + n, 0)); // 6
The accumulator's type is decided entirely by what you pass as the initial value. Always pass one.
reduce also receives the index and the source array, which is what lets it compute things that depend on position:
const scores = [10, 20, 30];
const average = scores.reduce((acc, n, i, arr) => {
const total = acc + n;
return i === arr.length - 1 ? total / arr.length : total;
}, 0);
console.log(average); // 20
This is the sort of thing reduce can do and map cannot, because each step has access to what came before it rather than only to its own element.
EXERCISE
2reduce() with Objects: Counting and Grouping
reduce() really shines when you need to build something more complex from an array: counting occurrences, grouping by category, or building lookup tables.
The accumulator does not have to be a number. When it is an object, reduce becomes the tool for counting, grouping and indexing, which is where it earns its place.
Counting occurrences:
const votes = ["yes", "no", "yes", "yes", "no"];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc;
}, {});
console.log(tally); // { yes: 3, no: 2 }
The accumulator starts as an empty object and gains a key the first time each value appears. (acc[vote] || 0) handles that first time, when the key does not exist yet and reading it gives undefined.
Grouping into arrays:
const people = [
{ name: "Ada", city: "London" },
{ name: "Alan", city: "London" },
{ name: "Grace", city: "New York" },
];
const byCity = people.reduce((acc, person) => {
if (!acc[person.city]) acc[person.city] = [];
acc[person.city].push(person.name);
return acc;
}, {});
console.log(byCity); // { London: ["Ada", "Alan"], "New York": ["Grace"] }
The guard on the second line creates the array the first time a city is seen. Without it, push would be called on undefined.
Indexing by id, which turns a linear search into a direct lookup:
const users = [
{ id: 7, name: "Ada" },
{ id: 9, name: "Alan" },
];
const byId = users.reduce((acc, u) => {
acc[u.id] = u;
return acc;
}, {});
console.log(byId[9].name); // "Alan"
Finding a user is now one property read rather than a scan of the array, which matters when you do it inside a loop over something else.
One caution: the accumulator here is the same object on every pass, and each callback modifies it and hands it back. That is deliberate and efficient, but it means reduce on an object accumulator is not free of mutation. What it does guarantee is that the object being mutated is the one you created as the initial value, so nothing outside the reduce is affected.
Pro Tip: Every one of these could be a
forloop, and the loop would be about as long. The reason to preferreduceis that the initial value and the combining step are named and separated, so the shape of the result is visible at a glance.
EXERCISE
3Function Chaining: map + filter + reduce Together
The ultimate power move: chain map, filter, and reduce in a single expression. Each step does one small job. Together, they handle complex data transformations.
The three methods are designed to be used together. Each returns a value the next can consume, so a pipeline reads as a description of the work rather than a set of instructions for performing it.
const orders = [
{ item: "book", price: 12, qty: 2, shipped: true },
{ item: "pen", price: 2, qty: 10, shipped: false },
{ item: "lamp", price: 40, qty: 1, shipped: true },
];
const shippedTotal = orders
.filter((o) => o.shipped)
.map((o) => o.price * o.qty)
.reduce((sum, value) => sum + value, 0);
console.log(shippedTotal); // 64
Three lines, three ideas: choose which orders count, work out what each is worth, add them up. Each step can be read on its own, and each can be commented out to see what it contributes.
The equivalent loop does the same work in one pass and mixes all three concerns:
let total = 0;
for (let i = 0; i < orders.length; i++) {
if (orders[i].shipped) {
total += orders[i].price * orders[i].qty;
}
}
console.log(total); // 64
This is not worse code. It is faster, because it walks the array once instead of three times, and for a very large array in a hot path that is the version to write. What it gives up is that you have to read every line to know what any of it does, and a change to the filtering condition means editing the middle of a block that also does arithmetic.
Order the steps so each does the least work:
const cheapTotal = orders
.filter((o) => o.shipped)
.filter((o) => o.price < 20)
.reduce((sum, o) => sum + o.price * o.qty, 0);
console.log(cheapTotal); // 24
Filter before you map or reduce, and put the most selective condition first. The final reduce here does the multiplication itself, which removes a pass without costing any clarity.
A pipeline returning the wrong type is nearly always a missing initial value:
console.log([].reduce((s, n) => s + n, 0)); // 0
An empty array after filtering is a normal outcome, not an error, and the initial value is what keeps it normal. Without it this line throws, and it will throw on the day the filter happens to match nothing.
Pro Tip: Build a chain one step at a time and log the result after each. Most pipeline bugs are a step returning something other than what the next step expects, and one log line finds it immediately.
