reduce() in an array
The reduce() method is one of the most powerful and versatile tools for working with arrays in JavaScript.
It is used to sequentially reduce an array to a single value: a number, a string, an object, an array, and so on.
Syntax
const result = array.reduce((accumulator, currentValue, index, array) => {
return newAccumulatorValue;
}, initialValue);Parameters:
| Argument | Description |
|---|---|
accumulator | the accumulated value (what is returned on each iteration) |
currentValue | the current array element |
index | the index of the current element |
array | the array itself |
initialValue | the accumulator's starting value (optional, but strongly recommended!) |
Example 1. Sum of numbers in an array
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10Explanation:
acc = 0(initial value)- 0 + 1 → 1
- 1 + 2 → 3
- 3 + 3 → 6
- 6 + 4 → 10
Example 2. Counting elements by a condition
const users = [
{ name: 'Tim', age: 25 },
{ name: 'Alex', age: 17 },
{ name: 'John', age: 30 }
];
const adultsCount = users.reduce((acc, user) => {
return user.age >= 18 ? acc + 1 : acc;
}, 0);
console.log(adultsCount); // 2
reduce()is often used for aggregation - counts, statistics, merges, and so on.
Example 3. Converting an array into an object
const fruits = ['apple', 'banana', 'cherry'];
const fruitMap = fruits.reduce((acc, fruit, index) => {
acc[index] = fruit;
return acc;
}, {});
console.log(fruitMap);
// { 0: 'apple', 1: 'banana', 2: 'cherry' }Very convenient for converting data into another structure.
Example 4. Merging an array of objects
const products = [
{ price: 10 },
{ price: 20 },
{ price: 30 }
];
const total = products.reduce((acc, item) => acc + item.price, 0);
console.log(total); // 60If you don't specify initialValue
const arr = [1, 2, 3];
const sum = arr.reduce((acc, num) => acc + num);
console.log(sum); // 6Here:
accon the first iteration =1(the first element)currentValue=2, then3
If the array is empty and there is no
initialValue→ you get an error:
[].reduce((acc, x) => acc + x); // TypeErrorSo always specify an initial value, especially for empty arrays.
Frequent errors
- Missing
return
arr.reduce((acc, num) => { acc + num }, 0); // undefinedFix it:
arr.reduce((acc, num) => { return acc + num }, 0);- Wrong type of initial value
['1', '2', '3'].reduce((acc, n) => acc + n, 0); // '0123', a stringConvert explicitly:
['1', '2', '3'].reduce((acc, n) => acc + Number(n), 0); // 6When to use reduce()
| Goal | Does reduce() fit |
|---|---|
| Sum or product of numbers | Yes |
| Counting statistics or totals | Yes |
| Converting an array into an object | Yes |
| Concatenating strings or arrays | Yes |
| Transforming each element | No - use map() instead |
| Selecting elements | No - use filter() instead |
In short:
reduce()is a "universal Swiss army knife": it reduces an array to a single final value.
A formula to remember:
arr.reduce((acc, elem) => newValue, initialValue)
Comparison with other methods
| Method | What it does | Returns | Can break out of the loop |
|---|---|---|---|
| forEach() | Iterates over elements | undefined | No |
| map() | Transforms elements | A new array | No |
| filter() | Selects elements | A new array | No |
| find() | Finds the first matching element | The element or undefined | Yes |
| reduce() | Reduces the whole array to one value | Any type (number, string, object, etc.) | Can via logic |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.