Introduction
Let’s first take a look at the official overview of this method: The reduce() method receives a function as an accumulator (accumulator), and each value in the array (from left to right) begins to reduce, Finally a value.
You must be a little confused like me. In fact, what reduce receives is a callback function to call each item in the array until the end of the array.
Let’s give an example and everyone will understand it clearly.
Suppose I have a string of arrays, and the arrays are all numbers. I want to calculate the sum of these numbers. Normally we would loop and add one by one. With reduce, we don’t have to go through so much trouble. We only use one line of code.
var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10
How does this method work?
reduce accepts a function, which has four parameters, namely:
1. Last value;
2. Current value;
3. Index of the current value;
4. Array;
Let’s take the above array as an example and print out these parameters to see:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; });
The result obtained is:
Analyzing this result, this callback function was called a total of 4 times, because the first time there was no previousValue, so it starts directly from the second item of the array and is called to the end of the array.
reduce also has a second parameter. We can use this parameter as the first parameter when calling callback for the first time. In the above example, because there is no second parameter, it is directly obtained from the second item of the array. At the beginning, if we give the second parameter 5, then the result is like this:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; },5);
The value of previousValue for the first call is passed in Instead of the second parameter, the function is called 5 times, which is the length of the array.
Reduce can help us accomplish many things easily. In addition to accumulation, it also flattens a two-dimensional array:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }, []); // flattened == [0, 1, 2, 3, 4, 5]