The reduce() Method in JavaScript
The reduce() method in JavaScript is used when we want to accumulate all elements of an array into a single value by performing specific operations. This is the go-to tool for obtaining aggregated results, such as sums, computed values, comparisons of number sequences, and more.
In this article, we will learn:
- What the reduce() method is
- How it works
- How it differs from map() and filter()
- How to write reduce() from scratch
Syntax
array.reduce(function(accumulator, currentValue, currentIndex, array) {
// returns the new value
}, initialValue);
Parameters
- accumulator – the value from the previous step (stores the result)
- currentValue – the current element
- currentIndex – the current index
- array – the entire array
- initialValue – the initial value (otherwise, the accumulator becomes the first element)
Simple Example
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function(acc, num) {
return acc + num;
}, 0);
console.log(sum); // 10
In this case, reduce() adds all the numbers, starting from the initial value of 0.
Difference from map() and filter()
- map() – used to create a new array of transformed values.
- filter() – used to select elements, returning a new array.
- reduce() – used to aggregate or compute values, resulting in a single value.
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
const sum = nums.reduce((acc, num) => acc + num, 0); // 15
Conclusion: map() and filter() return new arrays, while reduce() returns a single value.
Important Details
- If initialValue is not provided, the first element becomes the accumulator.
- You can perform complex operations like summation, multiplication, concatenation, object composition, etc.
- reduce() is used to combine all data into a single value.
Real-World Example
Here’s an example where we calculate the average of all elements in an array.
const numbers = [10, 20, 30, 40, 50];
const average = numbers.reduce(function(acc, num, index, array) {
acc += num;
if (index === array.length - 1) {
return acc / array.length;
}
return acc;
}, 0);
console.log(average); // 30
In this case, we sum each element and only divide by the array length at the end to get the average.
How the reduce() Method Works Internally
reduce() is associated with Array.prototype.
When we write:
[1, 2, 3].reduce(fn, 0);
It is the same as:
Array.prototype.reduce.call([1, 2, 3], fn, 0);
Let’s Write Our Own myReduce() Function
function myReduce(array, callback, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < array.length; i++) {
accumulator = callback(accumulator, array[i], i, array);
}
return accumulator;
}
Usage:
const nums = [1, 2, 3, 4];
const sum = myReduce(nums, function(acc, num) {
return acc + num;
}, 0);
console.log(sum); // 10
We Can Add It to the Array (for Educational Purposes)
Array.prototype.myReduce = function(callback, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
Usage:
const nums = [1, 2, 3, 4];
const sum = nums.myReduce((acc, num) => acc + num, 0);
console.log(sum); // 10
Notice how reduce() iterates through all elements and uses the previous result (accumulator) at each step.