js Array.reduce方法总结

181 阅读2分钟

reduce 累加器各种操作 (参考MDN)

reducer 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。 一个“reducer”函数,包含四个参数:

  • previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]
  • currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]
  • currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
  • array:用于遍历的数组。
1、累加数组对象 求和:
        const num = [{x:1},{x:2},{x:3}]

        num.reduce((accumulator,currentValue)=>{
            return accumulator + currentValue.x
        },0)
    
    
2、 将二维数组合并成一维数组

        const num = [[1],[2],[3]]
        const newsNum = num.reduce((accumulator,currentValue)=>{
        return accumulator.concat(currentValue)  || [...accumulator, ...currentValue]
        },[])
        
        
3、 计算数组中各个元素出现的次数

        const num = ["a", "b", "c", "a", "a", "a"];
        const newNum = num.reduce((accumulator, currentValue) => {
          if (currentValue in accumulator) {
            accumulator[currentValue]++;
          } else {
            accumulator[currentValue] = 1;
          }
          return accumulator;
        }, {});
        
        
        console.log(newNum);
        // 结果: {a: 4, b: 1, c: 1}
        

4、 按指定属性对obj分类
    const person = [
      { name: "A", age: 12 },
      { name: "B", age: 12 },
      { name: "C", age: 20 },
    ];

    function getAttrs(array, attrs) {
      return array.reduce((accumulator, currentValue) => {
        let key = currentValue[attrs];
        if (!accumulator[key]) {
          accumulator[key] = [];
        }
        accumulator[key].push(currentValue);
        return accumulator;
      }, {});
    }

    console.log(getAttrs(person, "age"));
    // 结果 {12: Array(2), 20: Array(1)}
    
5、 数组排序去重
     const num = [6, 1, 1, 2, 3, 3, 4, 5];
    let result = num.sort().reduce((accumulator, currentValue) => {
      if (
        accumulator.length === 0 || accumulator[accumulator.length - 1] !== currentValue
      ) {
        accumulator.push(currentValue);
      }

      return accumulator;
    }, []);

    console.log(result);
    //  [1, 2, 3, 4, 5, 6]
    
 6、 功能性管道函数
     // Building-blocks to use for composition
    const double = x => x + x
    const triple = x => 3 * x
    const quadruple = x => 4 * x

    // Function composition enabling pipe functionality
    const pipe = (...functions) => initialValue => functions.reduce(
        (acc, fn) => fn(acc),
        initialValue
    )

    // Composed functions for multiplication of specific values
    const multiply6 = pipe(double, triple)
    const multiply9 = pipe(triple, triple)
    const multiply16 = pipe(quadruple, quadruple)
    const multiply24 = pipe(double, triple, quadruple)

    // Usage
    multiply6(6)   // 36
    multiply9(9)   // 81
    multiply16(16) // 256
    multiply24(10) // 240
    
7、reduce 实现map 
    if (!Array.prototype.mapUsingReduce) {
  Array.prototype.mapUsingReduce = function(callback, initialValue) {
    return this.reduce(function(mappedArray, currentValue, currentIndex, array) {
      mappedArray[currentIndex] = callback.call(initialValue, currentValue, currentIndex, array)
      return mappedArray
    }, [])
  }
}

[1, 2, , 3].mapUsingReduce(
  (currentValue, currentIndex, array) => currentValue + currentIndex + array.length
) // [5, 7, , 10]