In a leaderboard, I came across the aforementioned problem. I render a list where I sort the players according to their points. Then I render them using the index 1
to get their position in the list. But in cases of equality, one gets second and the other third etc.
First I though maybe to have an index to each player, but that would be an overkill, since every time a player would change their points, I would have to change other players indexes too, to adjust the updated list.
I think, I need something that checks the points, and if they are the same as the following player, assign the same index. Then, if the following player has fewer points, get the index subtract the number of players that had the same points and give the result as his index.
Is that a good solution?
If someone would like to help, I have here a minimum reproducible example.
Thanks
CodePudding user response:
Here is what I did. I took the sorted list and looped over it and checked if the prev value was the same as the current value in the iteration. If the value are the same, there is no need to increase the position, but if different add one to the position.
https://codesandbox.io/s/players-with-same-points-forked-lkhcu6
CodePudding user response:
You can count
how many people have more points than the player, and the position for that player is that count 1
. You need an extra count for every player, but if the list is not huge, this can be a solution. For example:
let players = [
{ name: "John", points: 4 },
{ name: "Bill", points: 3 },
{ name: "Mark", points: 4 },
{ name: "Helen", points: 2 },
{ name: "Mary", points: 10 }
];
const list = players.sort((a, b) => (a.points < b.points ? 1 : -1));
function countPlayersMithMorePoints(points){
return players.filter(player => player.points > points).length 1;
}
players = players.map(player => {
return {
...player,
position: countPlayersMithMorePoints(player.points)
}
})
console.log(players)
So in this case. "Mark" and "Jhon" have 4 points... so both are in the second place. And Helen is on the fourth place. There is no third place.