JavaScript reduce and reduceRight: Summing, Grouping, Counting and Building Objects
How reduce works step by step, why you should almost always pass an initial value, common patterns (sum, max, count, group, index by key, flatten, statistics, pipelines), reduceRight, the spread-in-reduce performance trap, and when a loop or a dedicated method is clearer.
kvi5hnuCode Sprout team member6 min readOn this page
map turns an array into another array of the same length, and filter into a shorter one. reduce is the general case: it turns an array into any single value: a number, a string, an object, a Map, even another array. Sums, totals, counts, groupings and lookups are all reductions.
It's also the array method people find hardest to read at first, so let's take it slowly.
How reduce works
array.reduce(callback, initialValue)
callback(accumulator, element, index, array) → new accumulator
reduce keeps a running value, the accumulator. It starts as initialValue. For each element, it calls your callback with the current accumulator and the element, and whatever the callback returns becomes the accumulator for the next call. After the last element, the final accumulator is the result.
![reduce with an initial value of 0 over [4, 10, 6]: call 1 computes 0 + 4 = 4, call 2 computes 4 + 10 = 14, call 3 computes 14 + 6 = 20, the result](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-array-reduce-trace-3gpqgt36a2khp7jr.png)
const prices = [4, 10, 6];
const steps = [];
const total = prices.reduce((acc, price) => {
steps.push(`${acc} + ${price}`);
return acc + price;
}, 0);
console.log(total);
console.log(steps.join(" | "));
20
0 + 4 | 4 + 10 | 14 + 6
The two rules that make every reduction work: always return the accumulator from the callback, and choose an initial value of the type you want to end up with (0 for a sum, {} for an object, [] for an array, new Map() for a map).
Always pass an initial value
The initial value is optional. Without it, reduce uses the first element as the starting accumulator and begins with the second element. That works for simple sums, but it has three problems:
try {
[].reduce((a, b) => a + b); // 1. empty array: nothing to start with
} catch (err) {
console.log(err.name);
}
console.log([].reduce((a, b) => a + b, 0));
const cart = [{ price: 2, qty: 3 }, { price: 5, qty: 2 }, { price: 1, qty: 4 }];
console.log(cart.reduce((a, b) => a.price * a.qty + b.price * b.qty)); // 2. wrong types
console.log(cart.reduce((sum, item) => sum + item.price * item.qty, 0));
console.log(["1", "2"].reduce((a, b) => a + Number(b))); // 3. the first element isn't converted
console.log(["1", "2"].reduce((a, b) => a + Number(b), 0));
TypeError
0
NaN
20
12
3
- An empty array with no initial value throws a
TypeError. With one, the result is just the initial value. - When elements are objects, the first accumulator is an object, not a number. The second call receives a number as
a, anda.priceisundefined, givingNaN. - The first element skips your conversion logic:
"1"was used as-is, so+concatenated.
Pass the initial value every time unless you have a specific reason not to.
Common patterns
Totals and statistics
const temps = [14, 21, 9, 18];
const stats = temps.reduce(
(s, t) => ({ min: Math.min(s.min, t), max: Math.max(s.max, t), sum: s.sum + t }),
{ min: Infinity, max: -Infinity, sum: 0 },
);
console.log(stats, stats.sum / temps.length);
{ min: 9, max: 21, sum: 62 } 15.5
For just the largest or smallest number, Math.max(...temps) is clearer, but beware: Math.max() with an empty array gives -Infinity, and spreading a huge array (hundreds of thousands of elements) can exceed the engine's argument limit.
Summing floating-point numbers accumulates rounding error ([0.1, 0.2, 0.3] sums to 0.6000000000000001, article 12). ES2026's Math.sumPrecise(values) computes the exact sum; it's arriving in engines now, so check support before relying on it.
Counting
const words = ["to", "be", "or", "not", "to", "be"];
const counts = words.reduce((tally, word) => {
tally[word] = (tally[word] ?? 0) + 1;
return tally;
}, {});
console.log(counts);
const asMap = words.reduce((m, word) => m.set(word, (m.get(word) ?? 0) + 1), new Map());
console.log(asMap.get("to"));
{ to: 2, be: 2, or: 1, not: 1 }
2
Map.prototype.set returns the map, which makes it convenient as a one-line reducer. For keys from user data, the Map version also avoids inherited names like constructor (article 46).
Grouping and indexing
const people = [
{ name: "Ana", team: "red" },
{ name: "Bo", team: "blue" },
{ name: "Cy", team: "red" },
];
const byTeam = people.reduce((groups, p) => {
(groups[p.team] ??= []).push(p.name);
return groups;
}, {});
console.log(byTeam);
const teamOf = people.reduce((index, p) => {
index[p.name] = p.team;
return index;
}, {});
console.log(teamOf);
{ red: [ 'Ana', 'Cy' ], blue: [ 'Bo' ] }
{ Ana: 'red', Bo: 'blue', Cy: 'red' }
Both have dedicated alternatives now: Object.groupBy(people, (p) => p.team) (ES2024; article 48) for grouping, and Object.fromEntries(people.map((p) => [p.name, p.team])) for indexing. Prefer them: they say what they do.
Composing functions
Reduce can apply a list of functions in order, each one receiving the previous one's result:
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const slug = (s) => s.replace(/\s+/g, "-");
console.log(pipe(trim, lower, slug)(" Hello World Again "));
hello-world-again
reduceRight
reduceRight works the same way but goes from the last element to the first:
console.log(["a", "b", "c"].reduceRight((acc, letter) => acc + letter, ""));
console.log([2, 3, 2].reduceRight((acc, n) => n ** acc)); // 2 ** (3 ** 2)
cba
512
It's useful when the operation is naturally right-to-left, such as right-associative operators or function composition (compose(f, g)(x) means f(g(x)), so the last function runs first). For simply reversing a string, [...s].reverse().join("") is clearer.
The spread-in-reduce trap
This pattern looks elegant and appears in many tutorials:
const index = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
It's quadratic: every step copies the whole accumulator built so far into a new object. With 10 items, nobody notices. With 10,000, that's about 50 million property copies, enough to freeze a page for seconds. Mutating the accumulator, which you created yourself as the initial value, is perfectly safe:
const index = items.reduce((acc, item) => {
acc[item.id] = item; // the accumulator is ours: mutating it is fine
return acc;
}, {});
// or, clearer still:
const index2 = Object.fromEntries(items.map((item) => [item.id, item]));
The same applies to [...acc, x] instead of acc.push(x) when building arrays.
When not to use reduce
reduce can express almost anything, which is exactly why it's easy to overuse. Prefer:
| Instead of reduce for | Use |
|---|---|
| Transforming each element | map |
| Selecting elements | filter |
| Finding one element | find, some, every |
| Flattening | flat, flatMap (next article) |
| Grouping | Object.groupBy, Map.groupBy |
| Building an object from pairs | Object.fromEntries |
| Joining strings | join |
| Anything with several branches or early exit | a for...of loop |
A good rule of thumb: if the reducer callback is longer than a few lines or needs comments to follow, a loop with a clearly named variable will be easier to read.
Common questions
Can I stop reduce early?
No; it always visits every element. If you need to stop, use a for...of loop with break, or some/find.
Does reduce skip holes?
Yes. Like forEach, it skips holes in sparse arrays (article 55).
Does reduce modify the array?
No, not by itself. Your callback could mutate the elements or the array, but shouldn't. Mutating the accumulator you passed as the initial value is fine.
Why does reduce on strings with + give strange results?
+ concatenates when either operand is a string (article 31). Convert explicitly, acc + Number(x), and start from the numeric initial value 0.
Summary
reduce(callback, initial)carries an accumulator through the array; each callback return becomes the next accumulator, and the last one is the result.- Always return the accumulator, and always pass an initial value of the result's type; without it, empty arrays throw and the first element bypasses your logic.
- Common reductions: sums and statistics, counting, grouping, indexing, pipelines; but
Object.groupBy,Object.fromEntries,flat,joinandMath.maxare often clearer. reduceRightprocesses elements from last to first.- Don't spread the accumulator in each step (quadratic); mutate the accumulator you created instead.
- Use a loop when the reduction needs branches or early exit.
Practice Questions
What does this print?
console.log([1, 2, 3, 4].reduce((acc, n) => (n % 2 ? acc : acc + n), 0));
Answer
6. Odd numbers leave the accumulator unchanged; 2 and 4 are added.
Use reduce to turn [["a", 1], ["b", 2]] into { a: 1, b: 2 }, then name the built-in that does it directly.
Answer
pairs.reduce((obj, [key, value]) => { obj[key] = value; return obj; }, {})
The built-in is Object.fromEntries(pairs).
Why does this code return NaN?
[{ n: 1 }, { n: 2 }, { n: 3 }].reduce((a, b) => a.n + b.n)
Answer
Without an initial value, the first accumulator is the object { n: 1 }. The first call returns the number 3, so the second call computes 3.n + 3, which is undefined + 3, so NaN. Write .reduce((sum, item) => sum + item.n, 0).
Find the longest word in ["pear", "banana", "fig"] with reduce.
Answer
words.reduce((longest, w) => (w.length > longest.length ? w : longest), "")
Gives "banana". Starting from "" also handles an empty array.
Previous: Searching JavaScript Arrays: find, findIndex, findLast, includes, indexOf, some and every
Next: JavaScript Stacks, Queues and Flattening: push, pop, shift, unshift, concat, flat and flatMap

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.