如何基于游戏数组按玩家分组并累加对应团队得分生成积分榜?
基于游戏数组生成玩家积分榜
需求说明
需要从包含多场游戏的数组生成玩家积分榜:
- 每场游戏包含两队最终得分(
teamOneScore、teamTwoScore)以及参与玩家列表 - 每个玩家具备
team属性(1代表一队,2代表二队) - 根据玩家的
team属性,累加其所在团队在所有游戏中的得分 - 最终输出新增
totalScore属性的玩家数组(可移除team、image等非必要属性)
示例数据
var games = [ { 'id': '1', "teamOneScore": 10, "teamTwoScore": 5, 'players': [ { "username": "waters", "displayName": "Waters Adkins", "gender": "M", "image": null, "team": 2, "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1" }, { "username": "whitney", "displayName": "Whitney Winters", "gender": "F", "image": null, "team": 1, "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625" } ] }, { 'id': '4', "teamOneScore": 25, "teamTwoScore": 10, 'players': [ { "username": "waters", "displayName": "Waters Adkins", "gender": "M", "image": null, "team": 2, "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1" }, { "username": "whitney", "displayName": "Whitney Winters", "gender": "F", "image": null, "team": 1, "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625" } ] }, { 'id': '6', "teamOneScore": 10, "teamTwoScore": 5, 'players': [ { "username": "waters", "displayName": "Waters Adkins", "gender": "M", "image": null, "team": 2, "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1" }, { "username": "whitney", "displayName": "Whitney Winters", "gender": "F", "image": null, "team": 1, "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625" } ] } ];
解决方案
通过遍历游戏数组,以appUserId作为玩家唯一标识,累加对应团队得分:
function generatePlayerLeaderboard(games) { const playerMap = {}; games.forEach(game => { const { teamOneScore, teamTwoScore, players } = game; players.forEach(player => { const { appUserId, team } = player; // 获取当前游戏中玩家所属团队的得分 const gameScore = team === 1 ? teamOneScore : teamTwoScore; if (!playerMap[appUserId]) { // 初始化玩家信息,移除非必要属性 playerMap[appUserId] = { username: player.username, displayName: player.displayName, gender: player.gender, appUserId: player.appUserId, totalScore: 0 }; } // 累加总分 playerMap[appUserId].totalScore += gameScore; }); }); // 将映射对象转为数组返回 return Object.values(playerMap); } // 调用函数生成积分榜 const playerLeaderboard = generatePlayerLeaderboard(games); console.log({ players: playerLeaderboard });
预期结果
{ 'players': [ { "username": "waters", "displayName": "Waters Adkins", "gender": "M", "totalScore": 20, "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1" }, { "username": "whitney", "displayName": "Whitney Winters", "gender": "F", "totalScore": 45, "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625" } ] }
内容的提问来源于stack exchange,提问作者Jonathas Honor
相关产品推荐
相关产品推荐

