JavaScript数组万金油方法:reduce

109 阅读1分钟

[1,2,3,4].reduce((acc,item,index,arr)=>{},initValue)

acc:累加器,初始值未initValue

item:当前的数组项

index:索引

arr:完整数组

函数体内部返回结果为下一次循环中acc的值

如果使用变量接收最终结果

let a = [1,2,3,4].reduce((acc,item,index,arr)=>{},initValue), a为循环结束时acc的值。

部分使用场景:

1.数组求和

[1,2,3,4].reduce((acc,item)=>acc+item,0) //10

2.数组去重

let arr = [1, 2, 3, 1, 5, 8, 6, 1, 3, 2, 4, 5, 6, 1, 3, 5, 7, 8, 9, 5, 1, 2, 6, 6, 1]
let sortArr = arr.sort().reduce((acc,item)=>{
    if(acc.length===0||acc[length-1]!==item){
    acc.push(item)
    }
    return acc
},[])  //[1,2,3,4,5,6,7,8,9]


3.按属性分组

 const groupBy = (arr, attr) => {
            return arr.reduce((acc, item) => {
                let attrValue = item[attr]
                if (!(attrValue in acc)) {
                    acc[attrValue] = []
                }
                acc[attrValue].push(item)
                return acc
            }, {})
        }
        let arr = [
            { name: 'a', age: 20 },
            { name: 'a', age: 20 },
            { name: 'b', age: 21 }
        ]
        console.log(groupBy(arr, 'age'))
        
        /*======运行结果=======*/
        /*==
        {
          20:[ 
              { name: 'a', age: 20 **},
              { name: 'a', age: 20 }],
          21:[
              { name: 'b', age: 21 }]
        }
        */
      

4.功能型管道函数

 const double = x => x + x
       const triple = x => 3 * x
       const four = x => 4 * x
       const pipe = (...functions) => input => functions.reduce((acc, func) =>func(acc), input)
       const one = pipe(double, triple)
       console.log(one(6)) //36
       
/*
const pipe = (...functions) => input => functions.reduce((acc, func) =>func(acc), input)
等价于 function pipe(...functions){
        return function(input){
          return functions.reduce((acc,func)=>func(acc),input)
    }
}
*/