简体   繁体   中英

Javascrip iterating over a for loop - logic

Folks, I am extracting data from my collection into an array like so

obj = [{
  "PlayerName": "Satyajit Sahay",
  "Points": 83.83,
  "Rank": 1
},
{
  "PlayerName": "Chirag Galundia",
  "Points": 75.69,
  "Rank": 2
},
{
  "PlayerName": "Kashyap Kapoor",
  "Points": 70.91,
  "Rank": 3
}]

Around 190 such records. My effort is to iterate the array in a for loop. Then identify if the points are the same. If same I am assigning the same rank or else I am assigning a rank +1. Here is the code written so far

var ranking = 1
for (i = 0; i < obj[0].length; i++) {
  if (i > 0 && obj[0][i].Points < obj[0][i - 1].Points) {
    ranking++
    obj[0][i].Rank = ranking;
  } else if (i > 0 && obj[0][i].Points === obj[0][i - 1].Points) {
    obj[0][i].Rank = ranking;
    ranking++
  }
}

This works fine if 2 consecutive players have the same points. The minute the third player has the same rank it behaves weirdly. Can someone help?

Let's assume your array is sorted by points.

What you can do as algorithm is

  1. start with second record (i=1), with ranking = 1, step=1
  2. if score is less than previous record increase ranking by step and reset step, else increase step
  3. assign ranking
  4. go back to 2 until we have reach the end of the array

aka

let ranking=1;
let step=1
for(i=1; i<obj.length; i++){
   if(obj[i].points < obj[i-1].points){
        ranking += step;
        step = 1;
   } else {
        step++;
   }
   obj[i].ranking = ranking;
}

Some extras:

don't use var use let or const

don't forget you can start the loop further than 0, if everything has a i>0 it means we don't need the first iteration.

take a look at a array funciton ( forEach() sort() find() , ...) they could come handy

don't use upercase letter to name your variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM