Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-formulagoogle-sheets-querygoogle-sheets-macros

My question is about Google sheet looping through a range of cells and ranking scores


enter image description here

Embedded is an image of what I need to do for some teachers in the school system I work in. Column A has the scores, and in column B I need to be able to rank the scores. The rank number starts at 1 and should stay the same until there is a change in the score value and then it should increment by one. I know I need some sort of looping structure, but I don't know how to do that in Google Sheets or google application script. Does someone know how to do this using a loop? Thank you!


Solution

  • Try this:

    function scoreRanking() {
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName('Sheet1');
      var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
      var vA=rg.getValues();
      var rObj={};
      var s=1;//Initial rank value
      for(var i=0;i<vA.length;i++) {
        if(rObj.hasOwnProperty([vA[i][0]])) {
          vA[i][1]=rObj[vA[i][0]];
    
        }else{
          rObj[vA[i][0]]=s++;
          vA[i][1]=rObj[vA[i][0]];
        }
      }
      rg.setValues(vA);
    }