arr.reduce(callback,[initialValue])
reduce 为数组中的每一个元素依次执行回调函数callback
不包括数组中被删除或从未被赋值的元素,接受四个参数:
/**
* callback {function(prev, cur, index, arr)}
* prev 初始值(或者上一次回调函数的返回值)
* cur 当前元素值
* index 当前索引
* arr 调用 reduce 的数组
* initialValue 可选 传递给函数的初始值
**/
数组求和
var arr = [1,2,3,4,1];
var arr1 = []
var sum = arr1.reduce((prev,cur,index,arr) => {
return prev + cur;
},0)
console.log(sum) // => 11
数组求乘积
var mul = arr.reduce((x,y) => x*y)
console.log(mul) // => 24
求数组最大项
var max = arr.reduce((x,y) => Math.max(x,y))
console.log(max) // => 4
数组去重
var newArr = arr.reduce((x,y) => {
x.indexOf(y) === -1 && x.push(y)
return x;
},[])
console.log(newArr) // => [ 1, 2, 3, 4 ]
高级用法
1、计算数组中每个元素出现的次数
let arr = ['cwl','zgp','gpz','bdd','eq','sd','eq','cwl'];
let num = arr.reduce((x,y) => {
if(y in x){
x[y]++
}else{
x[y] = 1
}
return x
},{})
console.log(num) // => { cwl: 2, zgp: 1, gpz: 1, bdd: 1, eq: 2, sd: 1 }
2、将二维数组转化为一维
let arr = [[0,1,2],[5,8],[7,3]];
let newarr = arr.reduce((x,y) => x.concat(y),[]);
console.log(newarr) // => [ 0, 1, 2, 5, 8, 7, 3 ]
3、将多维数组转化为一维数组
let arr = [[0,1],[7,[8,9,10],[2,3,4,[44,55]]]]
let newArr = (arr) => {
return arr.reduce((x,y) => x.concat(Array.isArray(y)?newArr(y):y),[])
}
console.log(newArr(arr)) // => [ 0, 1, 7, 8, 9, 10, 2, 3, 4, 44, 55 ]