DEV Community

Discussion on: Daily Challenge #26 - Ranking Position

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

const addRanking = list => {
  let prevValue = undefined;
  let prevRanking = 1;
  list.sort((a,b) => {
    if (a.points === b.points) {
      if (b.name > a.name) {
        return -1;
      } else {
        return 1;
      }
    } else {
      return b.points - a.points;
    }
  }).forEach((el, idx) => {
    if (prevValue === el.points) {
      el.ranking = prevRanking;
    } else {
      el.ranking = idx + 1;
      prevValue = el.points;
      prevRanking = el.ranking;
    }
  });
};
Enter fullscreen mode Exit fullscreen mode

Live demo on Codepen.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

This could be considerably reduced by using ternary operators.

Collapse
 
nishu1343 profile image
nishu1343

Hi alvaro. Could u please explain what u did in this program by putting comments in ur codepen link. Im trying to understand😊

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

I updated the Codepen with comments. Let me know if more details are needed.

Thread Thread
 
nishu1343 profile image
nishu1343

Thanku alvaro😊