zoukankan      html  css  js  c++  java
  • 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;
          }, {});
        }
     
     
  • 相关阅读:
    luogu P3834 【模板】可持久化线段树 1(主席树) 查询区间 [l, r] 内的第 k 小/大值
    覆盖的面积 HDU
    Picture POJ
    Atlantis HDU
    Transformation HDU
    Tunnel Warfare HDU
    Agri-Net POJ
    Conscription POJ
    Brush (IV) LightOJ
    Throwing Dice LightOJ
  • 原文地址:https://www.cnblogs.com/yxfboke/p/12170490.html
Copyright © 2011-2022 走看看