首页 > 解决方案 > 使用 reduce 分组和求和

问题描述

我想返回一个由团队分组的数组,其中包含 gp、win、loss 的总和。我正在尝试通过减少来完成此操作,但是总数并没有加起来。这是我的代码...

const myArr = [
  {team: 'Red', gp: 3, win:2, loss:1},
  {team: 'Black', gp: 3, win:1, loss:2},
  {team: 'Red', gp: 10, win:8, loss:2}
]

let output = myArr.reduce(
  (acc, curr) => {
    acc[curr.team] = {
      gp: acc.gp + curr.gp,
      win: acc.win + curr.win,
      loss: acc.loss + curr.loss
    };
    return acc;
  }, {
    gp: 0,
    win: 0,
    loss: 0
  }
);

console.log(output);

此代码以我需要的格式返回数组,但是,gp、win、loss 没有相加,而是显示了最后一个数据点。

标签: javascriptreduce

解决方案


You need to take an empty object as accumulator and then you could take the wanted keys for adding.

const
    myArr = [{ team: 'Red', gp: 3, win: 2, loss: 1 }, { team: 'Black', gp: 3, win: 1, loss: 2 }, { team: 'Red', gp: 10, win: 8, loss: 2 }],
    keys = ['gp', 'win', 'loss'],
    output = myArr.reduce((acc, curr) => {
        acc[curr.team] = acc[curr.team] || Object.assign(...keys.map(k => ({ [k]: 0})));
        keys.forEach(k => acc[curr.team][k] += curr[k]);
        return acc;
  }, Object.create(null));

console.log(output);


推荐阅读