I'm using Google Apps Script to read a bunch of files in a Google Drive folder into an array, which all start with "Week #", where # is a number from 1 to 54. I then want to sort this array. Problem is, the string-based sort doesn't give me the result I want.
I know that Google Apps Script, like JavaScript, uses an alphabetical sorting method, so I would expect "Week 1..." to end up next to "Week 10..." instead of "Week 2...". Based on this answer, I wrote the sorter
function below that I thought would deal with that problem. Basically I grab the first number from the title and use that to compare, so when looking between "Week 1..." and "Week 10..." it will just compare the numbers 1 and 10.
function sorter(a, b) {
var aNum = a.replace("Week ", "");
aNum = aNum.substr(0, aNum.indexOf(' '));
var bNum = b.replace("Week ", "");
bNum = bNum.substr(0, bNum.indexOf(' '));
if (aNum < bNum) return -1;
if (aNum > bNum) return 1;
return 0;
}
function myFunction() {
var folder = DriveApp.getFolderById('18xeGSgRQ9nAc19qn_KCScbMmixZY0agU');
var query = "title contains 'Week '";
var search = folder.searchFiles(query);
var filelist = [];
while (search.hasNext()) {
var file = search.next();
filename = file.getName();
if (filename.startsWith('Week ')) {
filelist.push(filename);
}
}
filelist.sort(sorter);
for (var i=0; i<filelist.length; i++) {
Logger.log(filelist[i]);
}
}
Problem is, this doesn't sort as expected. I've looped through the array and added everything to the Logger, and this is what it looks like ...
[20-12-20 15:22:02:556 PST] Week 1 (Dec 30 - Jan 5)
[20-12-20 15:22:02:558 PST] Week 10 (Mar 2 - Mar 8)
[20-12-20 15:22:02:559 PST] Week 11 (Mar 9 - Mar 15)
[20-12-20 15:22:02:560 PST] Week 12 (Mar 16 - Mar 22)
[20-12-20 15:22:02:562 PST] Week 13 (Mar 23 - Mar 29)
[20-12-20 15:22:02:563 PST] Week 14 (Mar 30 - Apr 5)
[20-12-20 15:22:02:564 PST] Week 15 (Apr 6 - Apr 12)
[20-12-20 15:22:02:566 PST] Week 17 (Apr 20 - Apr 26)
[20-12-20 15:22:02:567 PST] Week 18 (Apr 27 - May 3)
[20-12-20 15:22:02:569 PST] Week 2 (Jan 6 - Jan 12)
[20-12-20 15:22:02:571 PST] Week 20 (May 11 - May 17)
[20-12-20 15:22:02:573 PST] Week 22 (May 25 - Jun 1)
[20-12-20 15:22:02:575 PST] Week 23 (Jun 1 - Jun 7)
[20-12-20 15:22:02:578 PST] Week 25 (Jun 15 - Jun 21)
[20-12-20 15:22:02:579 PST] Week 26 (Jun 22 - Jun 28)
... And so on.
I've stepped through the debugger, and it's definitely grabbing the number from the file names correctly ... is there a reason why the sort function isn't properly sorting?