Array.prototype.reduce()。

 

语法:arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
reducer 函数接收4个参数:
Accumulator (acc) (累计器)
Current Value (cur) (当前值)
Current Index (idx) (当前索引)
Source Array (src) (源数组)
描述:
您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。
例子:
    // 数组求和
    const sum = [0, 1, 2, 3].reduce((acc, cur) => acc + cur, 0);

    // 累加对象数组里的值
    const total = [{x: 1}, {x: 2}, {x: 3}].reduce((acc, cur) => acc + cur.x, 0);

    // 将二维数组转化为一维
    const flattened = [[0, 1], [2, 3], 4, 5].reduce((acc, cur) => acc.concat(cur), []);

    // 计算数组中每个元素出现的次数
    const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    const countedNames = names.reduce((allNames, name) => {
      if (name in allNames) {
        allNames[name] ++;
      } else {
        allNames[name] = 1;
      }
      return allNames;
    }, {})

    // 按属性对object分类
    const people = [
      {name: 'Alice', age: 21},
      {name: 'Max', age: 20},
      {naem: 'Jane', age: 20}
    ];
    function groupBy (objectArray, property) {
      return objectArray.reduce((acc, obj) => {
        const key = obj[property];
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(obj);
        return acc;
      }, {});
    }

 

 
 
posted @ 2020-01-09 11:24  木易锅巴  阅读(240)  评论(0编辑  收藏  举报