Reduce is a native method in JavaScript that acts on arrays. It is a high-order function. Reduce takes two arguments, a callback function that is applied to each value in the array, and an optional initial value for the accumulator. The accumulator stores a value that is altered over the course of reduce’s execution. Reduce returns a single value. If no initial value is provided, the first element of the array becomes the initial value of the accumulator, unless the array reduce is called on is empty, in which case an error will be thrown.
To make this a bit clearer here is a simple example, using reduce to add all of the numbers in an array:
let nums = [1, 2, 3];
let sum = nums.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0);
console.log(sum);
6
In this classic example, I have provided an initial value of 0 as the second argument in reduce(). The function iterates through the array, adding each value in the array to the accumulator and returns 6.
In this case, if I hadn't provided an initial value this example would still work because setting the initial value of the accumulator to the first item in the array would not affect the addition performed by reduce.
Another example:
let bools = [true, false, true, false, true];
let truths = bools.reduce((accumulator, currentValue) => {
if(currentValue){
accumulator++
}
return accumulator;
}, 0);
console.log(truths);
3
In this example, reduce iterates through the array bools and when the values in the array evaluate to true, it adds one to the accumulator. Because there are three values that are true in the array, this console logging truths will return to 3.
Reduce can return more than just a number though. For instance, it can return an array. Here is an example:
let nestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flatArray = nestedArray.reduce((accumulator, currentValue) =>{
return accumulator.concat(currentValue);
}, [0]);
console.log(flatArray);
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here, reduceiterates through the nested array and concatenates the accumulator with the current value in the array. Because I started with an initial value of [0], that is the value of the accumulator when it is concatenated with the first array in the nested array.
Reduce is a very powerful method that has many uses. It can tackle a wide range of iterative operations performing aggregation, manipulating data, and transforming. Learning to use reduce effectively will allow you to write cleaner and more succinct code.
Top comments (0)