DEV Community

Discussion on: Daily Challenge #26 - Ranking Position

Collapse
 
wheatup profile image
Hao • Edited

There's probably a better way which requires only one iteration?

const players = [
    {
        name: "John",
        points: 100,
    }, {
        name: "Bob",
        points: 130,
    }, {
        name: "Mary",
        points: 120,
    }, {
        name: "Kate",
        points: 120,
    },
];

players.sort((a, b) => {
    return (a.points == b.points ? a.name > b.name : a.points < b.points) || -1;
}).forEach((e, i, arr) => {
    e.rank = i && arr[i-1].points == e.points ? arr[i-1].rank : i + 1;
});

console.log(players);       // [{"name":"Bob","points":130,"rank":1},{"name":"Kate","points":120,"rank":2},{"name":"Mary","points":120,"rank":2},{"name":"John","points":100,"rank":4}]
Collapse
 
ceck profile image
Ceck

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