You can sort at the array level, just get the data from the sheet into the matrix and sort the matrix in several passes by selecting the column that you want to sort.
something like that:
function test(){ sortSheetOnColumn(2,3) } function sortSheetOnColumn(col1,col2){ var sh = SpreadsheetApp.getActiveSheet(); var data = sh.getDataRange().getValues();// get all data var header = data.shift(); data.sort(function(x,y){ // Note: sort method changes the original array // var xp = Number(x[col2-1]);// use these to sort on numeric values // var yp = Number(y[col2-1]); var xp = x[col2-1].toLowerCase();// use these for non-numeric values var yp = y[col2-1].toLowerCase(); // I used toLowerCase() for my use case but you can remove it or change it to whatever you need Logger.log(xp+' '+yp); // just to check the sort is OK return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col ascending }); data.sort(function(x,y){ // Note: sort method changes the original array // var xp = Number(x[col1-1]);// use these to sort on numeric values // var yp = Number(y[col1-1]); var xp = x[col1-1].toLowerCase();// use these for non-numeric values var yp = y[col1-1].toLowerCase();// Logger.log(xp+' '+yp); // just to check the sort is OK return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on column col ascending }); // and at the end take back the headers data.unshift(header); sh.getDataRange().setValues(data); }
or better, after Adam's comment:
function sortSheetOnColumn2(col1, col2) { var sh = SpreadsheetApp.getActiveSheet(); var data = sh.getDataRange().getValues();
but Michael answers, if smarter , using the built-in Range.sort method that I did not know about (at least about its advanced features).
source share