我想返回一个由小组分组的数组,其中包含gp,胜利,损失。我正在尝试通过减少来实现这一目标,但是总数并未增加。这是我的代码...
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不会被累加,而是显示最后一个数据点。
答案 0 :(得分:2)
您需要将一个空对象用作累加器,然后才能使用想要的键进行添加。
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);
答案 1 :(得分:0)
我将使用Set将项目减少到一个唯一的集合,然后将每个项目映射到一个新对象。
const teams = [{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 result = [...new Set(teams.map(t => t.team))].map(team => {
return {
team,
gp: teams.reduce((sum, val) => val.team == team ? sum + val.gp : sum, 0),
win: teams.reduce((sum, val) => val.team == team ? sum + val.win : sum, 0),
loss: teams.reduce((sum, val) => val.team == team ? sum + val.loss : sum, 0)
}
}, [])
console.log(result)