使用reduce来分组和求和 [英] Using reduce to group by and sum

查看:50
本文介绍了使用reduce来分组和求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个由团队分组的数组,其中总和是gp、win、loss.我试图通过减少来实现这一点,但是,总数并没有加起来.这是我的代码...

I want to return an array grouped by the team with gp, win, loss summed up. I'm trying to accomplish this with reduce, however, the totals are not adding up. Here's my code...

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 没有相加,而是显示了最后一个数据点.

This code returns the array in the format I need, however, the gp, win, loss is not summed up, instead it shows the last data point.

推荐答案

您需要将一个空对象作为累加器,然后您才能将想要的键添加.

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);

这篇关于使用reduce来分组和求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆