im trying to sort column "a" then sort column "b".
I have a column called "Categories", im ordering it alphabetically. Then I want to order "Subcategories" alphabetically too, respecting the first column order.
function autoSort() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet=ss.getSheetByName("Table");
const orderArray = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn()).getValues()
orderArray.sort(sortFunction)
sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).setValues(orderArray)
}
This is the function i use to sort the first column. How can I do to sort the second column?
var sortFunction= function(a,b){
if (a[4]>b[4]){return 1}
else if (b[4]>a[4]){return -1}
return 0
}
CodePudding user response:
As an alternative you could always use the Range.sort() method.
function autoSort() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet=ss.getSheetByName("Table");
const range = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn());
range,sort([{column: 1, ascending: true}, {column: 2, ascending: true}])
}
CodePudding user response:
The sort can be written to sort the second column(say Col6) instead of returning 0:
var sortFunction= function(a,b){
if (a[4]>b[4]){return 1}
else if (b[4]>a[4]){return -1}
// they're equal:
if (a[5]>b[5]){return 1}
else if (b[5]>a[5]){return -1}
return 0
}