gpt4 book ai didi

javascript - 对象数组获得具有唯一 ID 的总数

转载 作者:行者123 更新时间:2023-12-04 07:52:26 26 4
gpt4 key购买 nike

所以我有一个名为 playerScoresData 的对象数组我需要得到每个球员的总得分和犯规。
我的问题是我觉得我用的太多了 Iteration/Loops有更清洁的解决方案吗?

const playerScoresData = [
{
playerId: '1',
score: 20,
foul: 3
},
{
playerId: '1',
score: 5,
foul: 2
},
{
playerId: '2',
score: 30,
foul: 1
},
{
playerId: '2',
score: 10,
foul: 3
}
]

const main = () => {
let stats = []
let newData = {}
const uniqPlayerIds = [...new Set(playerScoresData.map(item => item.playerId))]

for (var x = 0; x < uniqPlayerIds.length; x++) {
newData = {
playerId: uniqPlayerIds[x],
totalScores: 0,
totalFouls: 0
}
let filteredData = playerScoresData.filter(data => data.playerId === uniqPlayerIds[x])
for (var y = 0; y < filteredData.length; y++) {
newData.totalScores += filteredData[y].score
newData.totalFouls += filteredData[y].foul
}
stats.push(newData)
}
return stats
}

console.log(main())

最佳答案

您可以简单地使用 .reduce()方法并以更方便的方式聚合数据:

const playerScoresData = [
{
playerId: '1',
score: 20,
foul: 3
},
{
playerId: '1',
score: 5,
foul: 2
},
{
playerId: '2',
score: 30,
foul: 1
},
{
playerId: '2',
score: 10,
foul: 3
}
];

const result = playerScoresData.reduce((acc, item) => {
acc[item.playerId] = acc[item.playerId] || {tScore:0, tFoul: 0}; // set default value if missing
acc[item.playerId].tScore += item.score;
acc[item.playerId].tFoul += item.foul;
return acc;
}, {});

console.log(result);

所以最后我们有一个结果对象,其中键是球员 ID,值是总得分和犯规的对象。

关于javascript - 对象数组获得具有唯一 ID 的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66890131/

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