We're back with another week of challenges!
Today, let's get a little creative and develop a ranking system where we can sort points and calculate the position of an individual or a team competing in a game/competition.
Note:
If two or more persons have the same number of points, they should have same position number and sorted by name (name is unique).
For example, Input structure:
[
{
name: "John",
points: 100,
},
{
name: "Bob",
points: 130,
},
{
name: "Mary",
points: 120,
},
{
name: "Kate",
points: 120,
},
]
Output should be:
[
{
name: "Bob",
points: 130,
position: 1,
},
{
name: "Kate",
points: 120,
position: 2,
},
{
name: "Mary",
points: 120,
position: 2,
},
{
name: "John",
points: 100,
position: 4,
},
]
Good luck!
This challenge comes from user kzm. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (13)
JavaScript
Live demo on Codepen.
This could be considerably reduced by using ternary operators.
Hi alvaro. Could u please explain what u did in this program by putting comments in ur codepen link. Im trying to understand😊
I updated the Codepen with comments. Let me know if more details are needed.
Thanku alvaro😊
My solution in clumsy Haskell:
Python
There's probably a better way which requires only one iteration?
i want to contribute my idea with your code. i hope u enjoy with that. Maybe it's shoter
players.sort((a, b) => {
return (a.points == b.points ? a.name > b.name : a.points < b.points) || -1;
}).map((e,i)=>({...e,position:(i+1)}))
Going functional in Perl:
Just a short one in Javascript
Edit: somehow I hadn't noticed the
position
bit 😳, so I've added that as a map call.Here it goes!
And the result:
Shouldn't John's position in the example be 3?