Reduce function
reduce()
Method applies a function to each element in the accumulator and array (left to right), reducing it to a single value.
invokes the specified callback function for all elements in the array. cumulative result , and this in Next call the callback function as parameter provided.
<script> = [1, 2, 3, 4]; = (accumulator, currentvalue) + = {+ ' | ' + currentvalue) ; return accumulator + currentvalue }; // 1 + 2 + 3 + 4 Console.log (Array1.reduce (reducer)); // Ten // 5 + 1 + 2 + 3 + 4 Console.log (Array1.reduce (Reducer, 5)); // the </script>
The output is as follows:
Grammar:
callback a function that executes each value in the array, containing four parameters:
accumulator:
The return value of the accumulator summation callback; It is the cumulative value returned when the callback was last called, or initialValue
(as shown below).
currentValue:
The element being processed in the array.
- Optional, the index of the current element being processed in the array.
currentIndex:
If provided initialValue
, the index number is 0, otherwise the index is 1.
- an optional , called array.
array:
reduce
initialValue:
Optional, used as the callback
value of the first parameter of the first call. If no initial value is provided, the first element in the array is used. A call to reduce on an empty array without an initial value will error.
Use the following :
1. Common usage:
var t = [0, 1, 2, 3, 4].reduce (function(accumulator, CurrentValue, Currentindex, array) { + ' | ' + currentvalue+ '--+ ' + currentindex + ' + ' + array ); return accumulator + currentvalue; }); Console.log (' t: ', T);
The output is as follows:
2. If you provide an initial value as reduce
the second parameter of the method, the following is the running process and the result:
var t = [0, 1, 2, 3, 4].reduce ((accumulator, CurrentValue, currentindex, array) = = {+ ' | ' + Curr Entvalue+ '--+ ' + currentindex + ' + ' + array ); return accumulator + currentvalue; (ten ); Console.log (' t: ', T);
The output is as follows:
3. Convert Two-dimensional arrays to one-dimensional
var flattened = [[0, 1], [2, 3], [4, 5]].reduce ( function(A, b) { return A.concat (b); },[]); Console.log (flattened);
The output is as follows:
4. count the occurrences of each element in the array
var names = [' Alice ', ' Bob ', ' Tiff ', ' Bruce ', ' Alice ']; var countednames = Names.reduce (function (allnames, name) { ' | ' + name ') ; if inch allnames) { Allnames[name]++ ; Else { = 1; } return allnames; }, {}); Console.log (countednames);
The output is as follows:
5. array de-weight
Let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; = Arr.sort (). Reduce (init, current) ={ if(init.length===0 | | init[init.length-1]!== Current) { Init.push (current); } return init; }, []); // [1,2,3,4,5]
The output is as follows:
Method of the array (Array.prototype.reduce () method)