Reduce & aggregation
Turn a list into a result
Lesson 11 of 20 · 10 min · Module 4: Reliable features
Sometimes a collection needs to become one result: a sum, a count, or a combined object. reduce carries an accumulator through every item.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Identify an accumulator
- Provide a suitable initial value
- Explain how an empty collection behaves
The idea
In items.reduce(callback, initialValue), the callback receives the current accumulator and the next item. Its return value becomes the accumulator for the next iteration.
const total = [5, 10, 15].reduce((sum, value) => sum + value, 0);
console.log(total); // 30
01Trace the accumulator
With values 5, 10, and 15, the accumulator starts at zero. It becomes 5, then 15, then 30. The final accumulator is the result of reduce.
02Keep the callback focused
Return the updated total each time. Avoid modifying lesson objects: aggregation should read values and produce a result, not rewrite the original collection.
Your turn
totalMinutes(lessons) to sum the minutes property of every lesson. An empty list returns 0, and the input should remain unchanged.What the checks look for
- Adds the minutes
- Handles an empty collection
- Handles a zero-length lesson
Take this with you
A suitable starting value is part of the function’s behavior, not just a syntax detail.