Javascript-reduce Method (Array)
explanation : the reduce () method receives a function as an accumulator (accumulator), an array
Each value in the (left-to-right) merge begins with a value.
Syntax: Arr.reduce (Callback,[initialvalue])
Parameters :
Callback: A function that executes each value in the array, containing four parameters
Previousvalue: The value returned by the last call to the callback, or the provided initial value (InitialValue)
CurrentValue: The element currently being processed in the array
Index: The current element is indexed in the array
Array: Call the arrays of reduce
InitialValue: The first argument to call callback as the first time.
Note: If you do not pass in the InitialValue parameter, Previousvalue is the first element of ARR when the callback function executes for the first time. If the incoming
InitialValue parameter, Previousvalue takes iniaialvalue when the callback function executes for the first time. InitialValue's role is to
Specifies an initial value before an array operation.
Give me a chestnut:
1 var arr = [1,2,3,4]; 2 var function (pre,cur) {3 return pre + cur; // Debug 4 }5 var egreduce = arr.reduce (add);
We look at the incoming arguments.
First time:
Second time:
Third time:
We pass in the InitialValue parameter:
1 var arr = [1,2,3,4]; 2 var function (pre,cur) {3 return pre + cur; 4 }5 var egreduce = Arr.reduce (add,20);
First time:
Second time:
Third time:
Fourth time:
You can see that the InitialValue parameter function is executed more than once to add the initial value of the InitialValue parameter to the array.
The use of the Reduce method
To find the maximum value in the array:
1 var arr = [2,34,45,23,12]; 2 var egmax = Arr.reduce (function(pre,cur) {3 return pre>cur? Pre:cur; 4 }); /45
Array flattening:
1 var arr = [2 [4],3 [4,5,6], [ 7,8,9]5 ]; 6 var eglink = Arr.reduce (function(pre,cur) {7 return pre.concat (cur); 8 }) [1, 2, 3, 4, 5, 6, 7, 8, 9]
Resources:
JavaScript | MDN
http://www.tuicool.com/articles/fURVN3m
Javascript-reduce Method (Array)