[英]How can I render 2 players of a list, that have the same points, at the same level, e.g. both second?
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.然后我使用
index + 1
渲染它们以在列表中获取它们的 position。 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谢谢
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.
如果相同则position不用加,不同则position加1。
https://codesandbox.io/s/players-with-same-points-forked-lkhcu6 https://codesandbox.io/s/players-with-same-points-forked-lkhcu6
You can count
how many people have more points than the player, and the position for that player is that count + 1
.您可以
count
有多少人比玩家拥有更多的分数,而该玩家的 position 就是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.
“Mark”和“Jhon”有 4 分……所以都排在第二位。 And Helen is on the fourth place.
海伦排在第四位。 There is no third place.
没有第三个地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.