Search code examples
javascriptarraysrankingleaderboard

JavaScript Rank Leaderboard


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

How would I give them a rank based on the leaderboard? eg. UserA is in the 1st Rank, UserC is in the 2nd Rank, etc.

It will look something like this:

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

Solution

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