
Mateen Kiani
Published on Fri Jun 27 2025·3 min read

The reduce method in JavaScript is a powerful tool to transform arrays into single values. Under the hood, it calls a callback on each item in the array, carrying an accumulator (the running total or object) along with the current element. This method can sum numbers, flatten arrays, build objects, and much more.
Tip: If you need to push or append items to a new array, you might first look at array manipulation methods before jumping into
reduce. Sometimes a simplemaporfilterplus concat is easier to read.
The signature of reduce is:
array.reduce((accumulator, currentValue, index, array) => {// return updated accumulator}, initialValue);
initialValue on first call).One of the simplest uses is summing an array of numbers:
const numbers = [1, 2, 3, 4, 5];const total = numbers.reduce((sum, n) => sum + n, 0);console.log(total); // 15
Why it works:
sum starts at 0.n is added to sum.You can group or index items easily:
const users = [{ id: 'a1', name: 'Alice' },{ id: 'b2', name: 'Bob' },{ id: 'c3', name: 'Carol' }];const userMap = users.reduce((map, user) => {map[user.id] = user.name;return map;}, {});console.log(userMap);// { a1: 'Alice', b2: 'Bob', c3: 'Carol' }
By transforming an array into an object, you can look up values by key in constant time.
You can chain filter, map, and reduce to handle complex data flows. For example, sum only even numbers:
const sumEven = [1, 2, 3, 4, 5].filter(n => n % 2 === 0).reduce((total, n) => total + n, 0);console.log(sumEven); // 6
Flow:
filter removes odd numbers.reduce sums remaining items.reduce uses a callback, brush up on JavaScript callbacks to avoid confusion.Tip: Use descriptive parameter names like
(cart, item)or(grouped, element)instead of(a, b).
Flatten arrays:
const nested = [[1,2], [3,4], [5]];const flat = nested.reduce((acc, arr) => acc.concat(arr), []);// [1,2,3,4,5]
Counting occurrences:
const fruits = ['apple','banana','apple','orange'];const count = fruits.reduce((tally, f) => {tally[f] = (tally[f] || 0) + 1;return tally;}, {});// { apple: 2, banana: 1, orange: 1 }
Promise chaining (serial execution):
const tasks = [task1, task2, task3];tasks.reduce((p, fn) => p.then(fn), Promise.resolve()).then(() => console.log('All done'));
The reduce method is a Swiss Army knife for arrays in JavaScript. From simple sums to building complex data structures, it covers a wide range of tasks in a concise way. By mastering its signature and following our tips on naming and initial values, you can write more functional and readable code. Next time you need to transform an array into a single value or data shape, ask yourself: could reduce make your code simpler?
Start applying reduce in small cases, follow clear naming, and avoid mutations. Happy coding!
