JavaScript 排名排行榜

JavaScript Rank Leaderboard

[
  [ 'UserA', 490 ],
  [ 'UserC', 175 ],
  [ 'UserD', 67 ],
  [ 'UserB', 26 ]
]

我如何根据排行榜给他们排名?例如。 UserA 排名第一,UserC 排名第二,依此类推

它将看起来像这样:

UserA: Rank 1
UserC: Rank 2
UserD: Rank 3
UserB: Rank 4

使用对象并使用排序函数对其进行排序

const results = {
  'UserA': { points: 490 },
  'UserB': { points: 26  },
  'UserC': { points: 175 },
  'UserD': { points: 67  }
}
const rank = Object.entries(results)
  .sort(([, a], [, b]) => b.points - a.points)
  .map((item, i) => {
    results[item[0]].rank = (i + 1)
    console.log(item[0], results[item[0]].rank)
    return `${item[0]}'s Rank: ${i+1}`
  })
console.log(results)

const findUserRank = user => rank.filter(entry => entry.includes(user))
const getUserRankOnly = user => results[user].rank
const getRankUser = ranking => Object.entries(results).filter(([key,val]) => val.rank===ranking).map(([key]) => key)


console.log("Users containing 'User':", findUserRank('User').join("\n"))
console.log("User with rank #3", getRankUser(3)[0])
console.log("UserC's rank:", getUserRankOnly('UserC'))

与嵌套数组相同

const results = [
  [ 'UserA', 490 ],
  [ 'UserC', 175 ],
  [ 'UserD', 67 ],
  [ 'UserB', 26 ]
];
const rank = results.slice(0)
  .sort(([, a], [, b]) => b - a)
  .map((item,i) => `${item[0]}'s Rank: ${i+1}`);

const getUserRank     = user => rank.filter(entry => entry.includes(user))
const getUserRankOnly = user => rank.filter(entry => entry.includes(user))[0].split(": ")[1]
const getRankUser     = ranking => rank.filter(entry => entry.endsWith(ranking))[0].split("'")[0]


console.log("Users containing 'User':",getUserRank('User').join("\n"))
console.log("Users containing 'UserC':",getUserRank('UserC')[0])
console.log("User with rank #3",getRankUser('3'))
console.log("UserC's rank:",getUserRankOnly('UserC')[0])