The reduce() method is one of many that can be applied to JavaScript arrays. It reduces the elements in an array to a single value with the help of a reducer function. You will learn about reduce() and the reducer function in this topic, and you'll also find out about the reduceRight() method.
Reduce method
The reduce() method reduces an array to a single value by executing the reducer function on the elements it contains.
To understand how reduce() works, let's start by examining its syntax:
let example = array.reduce(callback, initialValue);
A description of each component is given below:
array: the array to which thereduce()method is applied.callback: a mandatory argument used to reduce the array to a single value. Also known as a reducer function.initialValue: an optional argument utilized in the first invocation of the reducer function. If not specified, the reducer takes the first element of the array.
The callback (reducer function) takes four arguments. Its syntax is as follows:
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
The arguments that can be passed to the reducer function are:
accumulator: collects the return values of thecallbackfunction.currentValue: the value of the element that is currently being processed.currentIndex: the index of the current element (optional).array: the array to which thereduce()method is applied (optional).
Reduce example
Now, let's look at an example. We'll apply reduce() to an array so we can see how its arguments work internally:
let arr = [1, 3, 5, 7];
let summation = arr.reduce(function arraySum(sum, number) {
return sum + number;
});
console.log(summation); // 16
Here, sum is the accumulator that collects all the return values of the arraySum function, and number is the currentValue being processed by arraySum.
An initialValue isn't provided, so the accumulator (sum) is initially set to the first element of the array (which, in this case, is 1). Iteration then begins from the array's second element, and the arraySum function adds each number to sum. Once arraySum has been run to completion over the whole array, and the updated sum is returned.
Use of optional arguments
currentIndex and array are optional arguments, but passing them to the reducer function can be very useful. For example, we want to calculate the average of all the elements in an array. In this scenario, using array and currentIndex allows us to base our calculation on the length of the array without knowing its size:
let evenNumbers = [2, 4, 6, 8, 10];
let avg = evenNumbers.reduce((sum, number, currentIndex, array) => {
sum += number;
if (currentIndex == array.length - 1) {
return sum / array.length;
} else {
return sum;
}
});
console.log(avg); // 6
Here, currentIndex indicates the number of times the reducer function has looped through the array. And array is the original array to which the reducer function is being applied. So, as you can see, using these arguments makes it possible to calculate that the average value of the numbers in our example is 6.
Next, let's look at how the reduce() method works when an initialValue is supplied:
let oddNumbers = [1, 3, 5, 7];
let summation = oddNumbers.reduce(function arraySum(sum, number) {
return sum + number;
}, 4);
console.log(summation); // 20
In this example, the initialValue has been set to 4. This means that sum is initialized with 4 and the arraySum callback adds the iterated items to this initial value. The output of the above code is, therefore, 20.
initialValue isn't specified, the callback function will start its execution from the index 1, and the initial value of the accumulator will be the first element of the array. However, if an initialValue is provided, the callback function's execution will begin at the index 0.
ReduceRight method
Like the reduce() method, the reduceRight() method reduces an array to a single value. The difference is that it applies the reducer function to each array element in reverse order — moving from right to left.
The syntax of reduceRight() is as follows:
array.reduceRight(callback(accumulator, currentValue, currentIndex, array), initialValue)
The arguments in the reduceRight() method have the same meaning as those in the reduce() method.
Looking at an example should make reduceRight() easier to understand:
let numbers = [1, 4, 7];
let division = numbers.reduceRight((num1, num2) => {
return num1 / num2;
});
console.log(division); // 1.75
Here, the reduceRight() method is used to apply the division operation to each element of the array, and the result is 1.75. Order matters when dividing numbers! So, the output would have been different if we had used reduce() instead of reduceRight(), as shown below:
let numbers = [1, 4, 7];
let division = numbers.reduce((num1, num2) => {
return num1 / num2;
});
console.log(division); // 0.036Conclusion
You now know how to reduce an array to a single value using the reduce() and reduceRight() methods. These methods take two arguments: callback and initialValue. You have learned that the reducer function (callback) is invoked on the elements of the array, and it updates the accumulator value at each step. Also, once this process is complete, the accumulated value is returned. Don't forget that reduce() moves from left to right and reduceRight() moves from right to left!