[Solved] JavaScript Rank Leaderboard [closed]


Use an object and sort it using a sort function

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

Same with your nested array

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

3

solved JavaScript Rank Leaderboard [closed]