So I have an array of objects called playerScoresData
and I need to get the total of each players score and fouls.
My Problem is that I think I used too much Iteration/Loops
Is there a more cleaner solution ?
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())