DEV Community

loading...

Discussion on: Daily Challenge #26 - Ranking Position

Collapse
ynndvn profile image
La blatte • Edited

Here it goes!

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

const sortPlayers = (arr) =>
  arr.sort((a, b) => 
    b.points - a.points
    || a.name.localeCompare(b.name)
  )
  .map((p, i, l) => Object.assign(p, {position: i && !(l[i-1].points-p.points) ? l[i-1].position : i+1}));

And the result:

sortPlayers(players);
[
  {
    "name": "Bob",
    "points": 130,
    "position": 1
  },
  {
    "name": "Kate",
    "points": 120,
    "position": 2
  },
  {
    "name": "Mary",
    "points": 120,
    "position": 2
  },
  {
    "name": "John",
    "points": 100,
    "position": 4
  }
]
Forem Open with the Forem app