DEV Community

loading...

Discussion on: Daily Challenge #26 - Ranking Position

Collapse
willsmart profile image
willsmart • Edited

Just a short one in Javascript

Edit: somehow I hadn't noticed the position bit 😳, so I've added that as a map call.

ranked = players =>
  players
  .slice()
  .sort((a, b) => Math.sign(b.points - a.points) * 2 + a.name.localeCompare(b.name))
  .map((item, index, array) =>
    Object.assign(item, {
      position: index && item.points == array[index - 1].points ? array[index - 1].position : index + 1,
    })
  );

 players = [
  {name: 'b', points: 1},
  {name: 'b', points: 3},
  {name: 'b', points: 2},
  {name: 'a', points: 2},
  {name: 'c', points: 2}
];

console.log(JSON.stringify(ranked(players),null,2)); 
/* ^ [  {
    "name": "b",
    "points": 3,
    "position": 1
  },
  {
    "name": "a",
    "points": 2,
    "position": 2
  },
  {
    "name": "b",
    "points": 2,
    "position": 2
  },
  {
    "name": "c",
    "points": 2,
    "position": 2
  },
  {
    "name": "b",
    "points": 1,
    "position": 5
  }
]
*/
Forem Open with the Forem app