JavaScript lesson · 19 min
JavaScript Array reduce
Turn an array into one result, such as a total, summary object, or grouped count.
What you will practice
- Understand reduce as a way to build one result.
- Use an accumulator value.
- Calculate totals and grouped summaries.
What this means
`reduce` walks through an array and carries one result forward from item to item.
That carried result is often called the accumulator. It can be a number, string, array, object, Map, or any other value.
Reduce is powerful, but it can be harder to read than a loop. Use it when the final result shape is clear.
If this is your first time seeing this
reduce turns many values into one final result.
The accumulator is the running result. It starts with the initial value and changes after each array item.
Mini glossary
- reduce
- An array method that builds one result from many items.
- Accumulator
- The value that carries the running result through each step.
- Initial value
- The value the accumulator starts with.
Example from everyday life
reduce is like counting coins from a jar. You pick up one coin, add it to the running total, pick up the next coin, add again, and continue until one final total remains.
How it works step by step
- The code starts with an array of daily views.
- The first reduce adds every view count to one total number.
- The second reduce builds an object where each source name becomes a key.
- The final output shows both a simple total and a grouped summary.
Where you will use this
- Analytics code turns daily numbers into one monthly total.
- A shopping cart reduces line items into a final price.
- A report groups rows by category or status.
Before you run the code
When learning reduce, say the accumulator out loud: `total starts at 0, then each number is added to total`.
If reduce feels too magical, write the same code with a `for...of` loop first, then compare the two versions.
Common beginner mistakes
- Forgetting the initial value and getting surprising behavior.
- Making the reducer function too clever to read.
- Using reduce when a simple loop would be clearer for a beginner.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Add one more view row and recalculate the totals.
- Change `direct` to `social` and see the grouped object change.
- Rewrite the total calculation with a `for...of` loop.