Detailed explanation and example of reduce() in javaScript
Definition and usage
educe() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
grammar
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
parameter
parameter | description book |
---|---|
function(total,currentValue, index,arr) | required. A function to execute on each array element. Function parameters: |
total | required. The initial value, or the return value after the calculation is completed. |
currentValue | required. current element |
currentIndex | optional. the index of the current element |
arr | optional. the array object to which the current element belongs |
initialValue | optional. the initial value passed to the function |
example
var arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24
advanced method
Find the maximum value of an array item
var arr = [3,9,4,3,6,0,9];
var max = arr.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;})
console.log(max);// 输出:9
Array deduplication
var arr = [3,9,4,3,6,0,9];
var newArr = arr.reduce(function (prev, cur) {
prev.indexOf(cur) === -1 && prev.push(cur);
return prev;
},[]);
console.log(newArr );// 输出:[3, 9, 4, 6, 0]
Find the number of occurrences of a letter in a string
var str = 'asddfgdfasdqwesadsassdfg';
var res = str.split('').reduce((accumulator, cur) => {accumulator[cur] ? accumulator[cur]++ : accumulator[cur] = 1; return accumulator;}, {});
console.log(res);// 输出:{"a":4,"s":6,"d":6,"f":3,"g":2,"q":1,"w":1,"e":1}
flatten a 2D array
var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
var res = arr.reduce((x, y) => x.concat(y), []);
console.log(res); // 输出:[1, 2, 8, 3, 4, 9, 5, 6, 10]
That's all for now, if there is a better one, I hope you can add it in the comment area!