Reputation: 33
I was trying to custom sort a list using App Script for Google Sheets, basically I have a list of the months and I want them to appear as January, February, March... in the order of the months. This is an example of my list
The code I used in App Script is:
var sheet = SpreadsheetApp.getActive().getSheets()[0];
var range = sheet.getRange(1,3,sheet.getLastRow(),1);
var values = range.getValues();
var sortBy = {
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12
};
values.sort(function(a,b){
return sortBy[[a][0]] - sortBy[[b][0]];
});
How can I connect this code in App Script to my spreadsheet for the months to get sorted.
Upvotes: 0
Views: 859
Reputation: 64120
function sortMonths() {
const mA = [...Array.from(new Array(12).keys(),x => Utilities.formatDate(new Date(new Date().getFullYear(), x , 1),Session.getScriptTimeZone,"MMMM"))];
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const vs = sh.getRange(1,1,sh.getLastRow()).getValues().sort((a,b) => {
let vA = mA.indexOf(a[0]);
let vB = mA.indexOf(b[0]);
return vA-vB;//swap for descending
});//Data in column A
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}
Upvotes: 0
Reputation: 424
Try:
values.sort(([a],[b]) => sortBy[a] - sortBy[b]);
range.setValues(values);
Upvotes: 2