Introduced
Let's take a look at the official overview of this approach: the reduce()
method receives a function as an accumulator (accumulator), and each value in the array (left to right) begins to shrink, eventually to a value.
You must have looked just like me. A bit confused, in fact, reduce
received is a callback function, to call each of the array, until the end of the array.
Let's take an example and you'll understand.
Let's say I have a bunch of arrays with numbers in it and I want to figure out what the sum of these numbers is. Normally we would loop, then add, and reduce wouldn't be so much trouble, just one line of code.
var total = [0,1,2,3,4].reduce ((A, b) =>a + B); 10
How does this approach work?
reduce
Accept a function that has four parameters, respectively:
1, the last time the value;
2, the current value;
3, the index of the current value;
4, array;
Let's take the above array for example and print out these parameters to see:
[0, 1, 2, 3, 4].reduce (function (Previousvalue, CurrentValue, index, array) {return
previousvalue + currentvalue;
});
The results obtained are:
To analyze this result, this callback function was called 4 times, because the first time did not previousValue
, so directly from the second item of the array, one call to the end of the array.
reduce
There is also a second argument, which we can use as the first argument for the first call, which, callback
because there is no second argument, starts directly from the second item of the array, and if we give the second argument to 5, the result is this:
[0, 1, 2, 3, 4].reduce (function (Previousvalue, CurrentValue, index, array) {return
previousvalue + currentvalue;
},5);
The value of the first call previousValue
is replaced with the second argument passed in, and the function is called 5 times, which is the array length
.
reduce
can help us to do a lot of things easily, in addition to the accumulation, there is a flattened 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]
Summarize
I can think of the two commonly used, but there must be a lot of places to use. The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.