Basics
The reduce() is a method of Array class. It executes a reducer function on each element of the array resulting in a single output value. The reducer function will be given to reducer() function as a parameter.
Array.reduce Example
In example below, we have an array of numbers. Then we use reduce() method to create a single output value that will be the sum of all the original numbers.
var originalNumbers = [1, 2, 3, 4, 5];
const sum = originalNumbers.reduce((accumulator, currentValue, currentIndex, sourceArray) => {
console.log("accumulator: ", accumulator);
console.log("currentValue: ", currentValue);
console.log("currentIndex: ", currentIndex);
console.log("sourceArray: ", sourceArray);
return accumulator + currentValue;
});
console.log("originalNumbers: ", originalNumbers);
console.log("sum: ", sum);
Code Explanation
In line 1, we define an array of numbers. This is the original array and it will not change.
In line 3, we define a new variable called “sum” that will hold the final single output value. The reduce() method will iterate through the originalNumbers array and returns the value defined in line 8 to the next iteration.
The reduce() function takes four arguments:
1. Accumulator will hold the sum during the iterations. In the end it will be the final single output value that will be returned.
2. currentValue holds the current element of the originalArray.
3. currentIndex is the number of the current element being processed.
4. sourceArray is the originalArray. It doesn’t change.
In line 8, the code returns the previous sum (in accumulator) added by currentValue to the next iteration.
In line 10, we print the originalArray to console. It should result "originalNumbers: [1, 2, 3, 4, 5]” .
In line 11, we print the newArray to console. It should result “sum: 15”.