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}]
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)}))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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)}))