Google Script sort 2D Array by any column

前端 未结 3 651
故里飘歌
故里飘歌 2020-12-21 06:42

I had a asked an earlier question about retrieving records from a database, here: Retrieving Records from a Google Sheet with Google Script

I\'m fairly comfortable w

3条回答
  •  攒了一身酷
    2020-12-21 07:10

    The array.sort method can have a function argument to choose on what part you want to sort. Code goes like this :

        array.sort(function(x,y){
          var xp = x[3];
          var yp = y[3];
    // in this example I used the 4th column... 
          return xp == yp ? 0 : xp < yp ? -1 : 1;
        });
    

    EDIT

    Following your comment, here is a small demo function that should help to understand how this works.

    Instead of using short form if/else condition I used the traditional form and splitted it in 3 lines to make it easier to understand.

    function demo(){
      // using a full sheet as array source
      var array = SpreadsheetApp.getActive().getActiveSheet().getDataRange().getValues();
      Logger.log('Unsorted array = '+array);
      array.sort(function(x,y){
    // in this example I used the 4th column... 
        var compareArgumentA = x[3];
        var compareArgumentB = y[3];
        // eventually do something with these 2 variables, for example Number(x[0]) and Number(y[0]) would do the comparison on numeric values of first column in the array (index0) 
        // another example x[0].toLowerCase() and y[0].toLowerCase() would do the comparison without taking care of letterCase...
        Logger.log('compareArgumentA = '+compareArgumentA+' and compareArgumentB = '+compareArgumentB);
        var result = 0;// initialize return value and then do the comparison : 3 cases
        if(compareArgumentA == compareArgumentB ){return result }; // if equal return 0
        if(compareArgumentA < compareArgumentB ){result = -1 ; return result }; // if A compareArgumentB ){result = 1 ; return result }; // if a>B return 1
        }
                );
      Logger.log('\n\n\nSorted array = '+array);
    }
    

    I added a couple of Logger.log to check starting, intermediate and final values. Try this in a spreadsheet.

    Hoping this will help.

提交回复
热议问题