.reduce()
Array method that processes each element and accumulates a single result. Can produce a number, string, object, array — anything.
When to use it
- Summing / counting — total a list of numbers
- Grouping — build an object keyed by a category
- Flattening — collapse nested arrays into one
- Building lookup tables — array of objects → object keyed by ID
- Pipeline — when
.map()+.filter()isn’t enough
Anatomy
const result = array.reduce((accumulator, element, index, array) => {
// accumulator — the running total (starts as initialValue)
// element — the current item
// return the updated accumulator
return accumulator
}, initialValue)At a glance
| Parameter | What it is |
|---|---|
accumulator | The running result — whatever you returned last iteration |
element | Current item being processed |
index | Position in the array (0-based) |
initialValue | Starting value for the accumulator (always provide this) |
| Return value | The final accumulator after all elements |
1. Simple — sum an array
const nums = [10, 20, 30]
const total = nums.reduce((sum, n) => sum + n, 0)
// iteration 1: sum=0, n=10 → 10
// iteration 2: sum=10, n=20 → 30
// iteration 3: sum=30, n=30 → 60
total // 602. Intermediate — build a lookup table
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Carol' },
]
const byId = users.reduce((map, user) => {
map[user.id] = user // key each user by their id
return map
}, {})
byId[2] // { id: 2, name: 'Bob' } — O(1) lookup instead of .find()3. Advanced — group by category
const transactions = [
{ category: 'food', amount: 12 },
{ category: 'transport', amount: 30 },
{ category: 'food', amount: 8 },
{ category: 'transport', amount: 15 },
]
const totals = transactions.reduce((groups, tx) => {
groups[tx.category] ??= 0 // initialize if missing
groups[tx.category] += tx.amount // accumulate
return groups
}, {})
// { food: 20, transport: 45 }Object.groupBy() (ES2024) handles the grouping, but reduce gives you full control to transform while grouping.
Gotchas
Always provide an initial value
// without initial value, reduce uses the first element as the accumulator
[].reduce((sum, n) => sum + n) // TypeError: Reduce of empty array with no initial value
[].reduce((sum, n) => sum + n, 0) // 0 — safe with initial valueDon’t overcomplicate — prefer map/filter when possible
// this works but is harder to read than map
const doubled = nums.reduce((arr, n) => {
arr.push(n * 2)
return arr
}, [])
// just use map
const doubled = nums.map(n => n * 2) // clearerRelated
- .map() — simpler choice when output is same-length array
- .filter() — simpler choice when you’re just keeping/discarding
- Object.fromEntries() — alternative to reduce for building objects from arrays
- Array — the full list of array methods
Last updated on