The reduce() method in JavaScript
Details, examples, practice
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:
array.reduce(function(accumulator, currentValue, currentIndex, array) { // returns the new value }, initialValue);
Parameters
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.
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.
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.
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);
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
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.