【问题标题】:Array of Objects get total with unique ids对象数组获得具有唯一 ID 的总数
【发布时间】: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())

【问题讨论】:

  • 您应该在提问之前搜索已回答的问题。通过简单的搜索,您可以找到与此问题相关的帖子。 linklink

标签: javascript node.js


【解决方案1】:

您可以简单地使用.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,值是总得分和犯规的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2011-05-12
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多