gpt4 book ai didi

javascript - Reduce 方法 - 无法获得两个单独的结果

转载 作者:行者123 更新时间:2023-11-30 14:29:54 24 4
gpt4 key购买 nike

我有一个这样的数组:

   const arr = [
[{rivals: ['player1','player2'], winner: "player1", player1Scored: 2, player2Scored: 1}],
[{rivals: ['player1','player3'], winner: "none", player1Scored: 2, player3Scored: 2}],
[{rivals: ['player2','player3'], winner: "player3", player2Scored: 1, player3Scored: 3}],
[{rivals: ['player1','player4'], winner: "none", player1Scored: 1, player4Scored: 1}]
]

我需要计算每个玩家的得分,所以它看起来像这样:

{player1Scored: 5, player2Scored: 2, player3Scored: 5, player4Scored:1}

我试过这个:

let scoreResult = arr.reduce((result, {0: obj}) => {
obj.rivals.forEach(rival => result[`${rival}Scored`] = result[`${rival}Scored`] || 0);

obj.rivals.forEach(rival => result[`${rival}Scored`] += obj.player1Scored)

return result;
}, {});

我的错误是我将一个玩家的点数分配给了两个玩家但无法解决这个问题。

谢谢你的帮助

最佳答案

要回答这个问题,您有一个包含单个对象的嵌套数组。您可以对数组进行解构并将第一个项目作为对象。

然后从 rivals 数组中取出名字并添加分数。

const
array = [[{ rivals: ['player1', 'player2'], winner: "player1", player1Scored: 2, player2Scored: 1 }], [{ rivals: ['player1', 'player3'], winner: "none", player1Scored: 2, player3Scored: 2 }], [{ rivals: ['player2', 'player3'], winner: "player3", player2Scored: 1, player3Scored: 3 }], [{ rivals: ['player1', 'player4'], winner: "none", player1Scored: 1, player4Scored: 1 }]],
result = array.reduce((r, [o]) => {
o.rivals.forEach(k => r[k + 'Scored'] = (r[k + 'Scored'] || 0) + o[k + 'Scored']);
return r;
}, Object.create(null));

console.log(result);

关于javascript - Reduce 方法 - 无法获得两个单独的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51369801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com