javascript - 使用 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 没有相加,而是显示了最后一个数据点。
解决方案
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);
推荐阅读
- python - 如果满足条件,只执行一次循环
- python - n/ 出现在 .readline()
- python - Python Cassandra 无法完成对任何主机的操作
- pygame - 如何对我的乒乓球游戏进行编程以在 python 中有一个 npc?
- python - 如何从python中的文件中提取不同行的某些数据
- java - JDBC 未将数据插入 MS SQL Server
- python - Python:csv到pickle表示,回到csv文件内容混乱
- c# - 如何使用 Newtonsoft 在 C# 中反序列化包含对象的 JSON 数组
- python - 我的程序只能识别泡菜文件中的第一对值
- javascript - 尽管应用了正确的 CSS 规则,但按钮没有水平居中