Lesson 3 of 80
The one array method that can express all the others — and a way of thinking that turns a scary problem into one small step, repeated.
15 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
What two things does reduce need to work?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
reduce walks a list once, carrying a running result. You give it two things: a starting value, and a step that answers "given the result so far and the next item, what's the new result?"
That's it. Every loop that builds up an answer is secretly a reduce.
When a problem feels big — "group these orders by month and total each" — don't solve the whole thing. Solve one step: given the tally so far and one order, where does it go? Then let reduce repeat that step across the list.
const orders = [
{ month: "Jan", amount: 40 },
{ month: "Feb", amount: 10 },
{ month: "Jan", amount: 25 },
];
const totals = orders.reduce((acc, order) => {
acc[order.month] = (acc[order.month] ?? 0) + order.amount;
return acc; // always return the running result
}, {}); // start empty
// totals -> Jan 65, Feb 10
You never had to think about the whole list — only "one order, into the tally." That's the trick for logic that feels weak: find the single repeatable step, and let the machinery repeat it.
reduce walks a list once, carrying a running result — the accumulator.
undefined."Implement map using reduce" is a classic. It checks whether you see that these aren't separate tricks — they're the same idea (a higher-order function walking a list) wearing different clothes.