目录
参数
1. 数组求和、求乘积
2. 累加数组中对象的值
3. 计算数组中每个元素出现的次数
4. 数组去重
5. 二维数组变一维数组
6. 将多维数组转化为一维
7. 根据属性把对象分类
|
||||||||||
initialValue | 可选。作为初始值传递给函数的值。 |
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
注释:对没有值的数组元素,不执行 reduce() 方法。
注释:reduce() 方法不会改变原始数组。
1. 数组求和、求乘积
let num = [1, 2, 3, 4, 5] let result1 = num.reduce((sum, n) => sum + n, 0) console.log(result1); // 15 // let result2 = num.reduce((sum, n) => sum * n) let result2 = num.reduce((sum, n) => sum * n, 1) console.log(result2); // 120
2. 累加数组中对象的值
let numObj = [{n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}] let result3 = numObj.reduce((sum, obj) => sum + obj.n, 0) console.log(result3); // 15
3. 计算数组中每个元素出现的次数
let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'red'] let countColor = colors.reduce(function(all, color){ if(color in all) { all[color]++; } else { all[color] = 1; } return all; }, {}); console.log(countColor); // {blue: 1, green: 1, indigo: 1, orange: 1, purple: 1, red: 2, yellow: 1}
4. 数组去重
let arr = [1, 2, 3, 4, 4, 1] let newArr = arr.reduce((pre,cur)=>{ if(!pre.includes(cur)){ return pre.concat(cur) }else{ return pre } },[]) console.log(newArr); // [1, 2, 3, 4]
5. 二维数组变一维数组
let twoArray = [[0, 1], [2, 3], [4, 5]] let oneArray = twoArray.reduce((arr, val) => arr.concat(val), []) console.log(oneArray); // [0, 1, 2, 3, 4, 5]
6. 将多维数组转化为一维
let moreArr = [[0, 1], [2, 3], [4,[5,6,7]]] const resultArr = function(moreArr){ return moreArr.reduce((pre,cur) => pre.concat(Array.isArray(cur) ? resultArr(cur) : cur), []) } console.log(resultArr(moreArr)); // [0, 1, 2, 3, 4, 5, 6, 7]
7. 根据属性把对象分类
let peopleInfo = [ {name: 'aaa', age: 15, sex: '男'}, {name: 'bbb', age: 16, sex: '女'}, {name: 'ccc', age: 15, sex: '女'} ] function groupBy(objectArray, property) { return objectArray.reduce((resultObj, obj) => { var key = obj[property] if(!resultObj[key]) { resultObj[key] = [] } resultObj[key].push(obj) return resultObj; }, {}) } let peopleAgeGroup = groupBy(peopleInfo, 'age') console.log(peopleAgeGroup); // {15: [{name: "aaa", age: 15, sex: "男"}, {name: "ccc", age: 15, sex: "女"}],16: [{name: "bbb", age: 16, sex: "女"}]} let peopleSexGroup = groupBy(peopleInfo, 'sex') console.log(peopleSexGroup); // {男: [{name: "aaa", age: 15, sex: "男"}], 女: [{name: "bbb", age: 16, sex: "女"}, {name: "ccc", age: 15, sex: "女"}]}
http://t.csdnimg.cn/Oe0x4