reduce() 方法

定义

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

注意:

        1. reduce() 对于空数组是不会执行回调函数的。

        2. 当提供了初始值initialValue,则第一次执行回调函数时previousvalue就是initialValue,则currentValue是数组第一项;如果没有提供初始值,则previousvalue是数组第一项,currentValue是数组第二项。

语法:

array.reduce( function( total, currentValue, currentIndex, arr ),  initialValue )

reduce() 方法

reduce的常用方法 ( 最好设置默认值 )

1. 数组求和

let numbers = [1, 2, 3, 4, 5]
let result1 = numbers.reduce((sum, n) => sum + n, 0)
console.log(result1); // 15

2. 累加数组中对象的值

let numberObj = [{n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}]
let result2 = numberObj.reduce((sum, obj) => sum + obj.n, 0)
console.log(result2); // 15

3. 计算数组中每个元素出现的次数

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'red']
let countColor = colors.reduce(function(allColors, color){
    if(color in allColors) {
        allColors[color]++;
    } else {
        allColors[color] = 1;
    }
    return allColors;
}, {});
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 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: "女"}]}

上一篇:2021-09-04


下一篇:case when else end使用