【发布时间】:2021-03-31 14:48:53
【问题描述】:
所以我有一个名为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())
【问题讨论】:
标签: javascript node.js