Sunday 15 May 2011

Google Script sort 2D Array by any column -



Google Script sort 2D Array by any column -

i had asked before question retrieving records database, here: retrieving records google sheet google script

i'm comfortable manipulating arrays , creating own sorting algorithms, want utilize existing array.sort() method organize info because of speed. i'm finding can utilize sort 2d array first column of data, can't find syntax sort on different column of data, other first.

the closest i've found this: google apps script aditional sorting rules. however, these inputs haven't worked me. here next code, array, tabledata:

tabledata.sort([{ column: 1}]);

=>typeerror: (class)@4dde8e64 not function, object. (line 49, file "sorttablebycol")

tabledata.sort([{column: 1, ascending: true}]);

=> typeerror: (class)@4d89c26e not function, object. (line 50, file "sorttablebycol")

what proper syntax choosing column of info sort on?

the array.sort method can have function argument take on part want sort. code goes :

array.sort(function(x,y){ var xp = x[3]; var yp = y[3]; // in illustration used 4th column... homecoming xp == yp ? 0 : xp < yp ? -1 : 1; }); edit

following comment, here little demo function should help understand how works.

instead of using short form if/else status used traditional form , splitted in 3 lines create easier understand.

function demo(){ // using total sheet array source var array = spreadsheetapp.getactive().getactivesheet().getdatarange().getvalues(); logger.log('unsorted array = '+array); array.sort(function(x,y){ // in illustration used 4th column... var compareargumenta = x[3]; var compareargumentb = y[3]; // these 2 variables, illustration number(x[0]) , number(y[0]) comparing on numeric values of first column in array (index0) // illustration x[0].tolowercase() , y[0].tolowercase() comparing without taking care of lettercase... logger.log('compareargumenta = '+compareargumenta+' , compareargumentb = '+compareargumentb); var result = 0;// initialize homecoming value , comparing : 3 cases if(compareargumenta == compareargumentb ){return result }; // if equal homecoming 0 if(compareargumenta < compareargumentb ){result = -1 ; homecoming result }; // if a<b homecoming -1 (you can alter of course of study , invert sort order) if(compareargumenta > compareargumentb ){result = 1 ; homecoming result }; // if a>b homecoming 1 } ); logger.log('\n\n\nsorted array = '+array); }

i added couple of logger.log check starting, intermediate , final values. seek in spreadsheet.

hoping help.

google-apps-script google-spreadsheet

No comments:

Post a Comment