Learn JavaScript
❯ arrays.reduce

reduce: Folding to One Value in JavaScript

$concept

reduce folds an array into a single value with an accumulator: [1,2,3].reduce((t, n) => t + n, 0) sums to 6. The seed (0 here) sets the accumulator's start and type β€” sums, products, objects, strings, even other arrays all fold from the right seed.

Omitting the seed starts from element zero (and throws on empty arrays) β€” always pass it explicitly. reduce expresses any aggregation, but readability rules: sums and products yes, labyrinthine multi-jobs better as explicit loops.

$how it works
1

Accumulator plus element

(total, n) => total + n runs per element, threading total through β€” the fold itself.

2

Seed sets type and start

0 for sums, 1 for products, {} for grouping, [] for flattening β€” the seed shapes the entire result.

3

Always pass the seed

Seedless reduce starts at index 1 and throws on [] β€” explicit seeds remove both hazards.

4

Keep folds focused

One aggregation per reduce; tangled multi-accumulators belong in readable loops instead.

$example
let nums = [1, 2, 3, 4];
let sum = nums.reduce((t, n) => t + n, 0);
let grouped = nums.reduce((g, n) => {
(g[n % 2 ? "odd" : "even"] ||= []).push(n);
return g;
}, {});
console.log(sum, grouped.even.length);
Output
10 2
1Sum folds 1+2+3+4 from seed 0 to 10.
2Grouping folds into {odd:[1,3], even:[2,4]} β€” object accumulation from {} seed.
310 and 2 (evens count) print β€” scalar and structural folds side by side.
$use cases
Sums, products, and averages from numeric arrays
Grouping (by key) and counting (by predicate) into objects
Flattening one level with concat-seeded reduces (or flat())
Composing pipelines: map/filter then a final reduce

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.