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

1
  • You should search for answered questions before you ask your question. With a simple search you can find posts related to this question. link link Commented Mar 31, 2021 at 14:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.