ECMAScript 5 also added two methods for merging arrays: reduce () and reduceright (). Both of these methods iterate over all the items of an algebraic group and then build a value that is ultimately returned. where the reduce () method starts with the first item in the array and traverses through to the end. The Reduceright () begins with the last item in the array and traverses forward to the first item. The reduce () and reduceright () functions receive 4 parameters: the previous value is the index array object of the current value entry. This function returns any value that is automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second is the second item of the array.
1 var values = [1,2,3,4,5]; 2 var sum = values.reduceright (function (Prev,cur,index,array) { 3 return prev+cur; 4 }); 5 // 15
Code Analysis: First execute callback function, Prev=1, cur=2. Second time prev=3, cur=3. This process continues until each item in the array is accessed again, and the result is returned. About the compatibility of reduce () and Reduceright (): ie9+, FF, Safari, Opear 10.5 and Chrome.
JavaScript Merge method reduce () and reduceright ()