2

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())
code.cycling
  • 1,246
  • 2
  • 15
  • 33
  • You should search for answered questions before you ask your question. With a simple search you can find posts related to this question. [link](https://stackoverflow.com/questions/38294781/how-to-merge-duplicates-in-an-array-of-objects-and-sum-a-specific-property) [link](https://stackoverflow.com/questions/19233283/sum-javascript-object-propertya-values-with-same-object-propertyb-in-array-of-ob) – Eagleclaw Mar 31 '21 at 14:55

1 Answers1

2

You can simply use the .reduce() method and aggregate the data in a bit more convenient way:

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);

So in the end we have a result object, where keys are players ids and value is an object of total score and fouls.

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52