简体   繁体   中英

Google script to sort array by first 7 digits of each element

I have an array that contains the URL and name of each folder in a folder. Each folder name has the date included in it in YYMMDD format, for example: 170105_remainingfoldername. I need to sort this array descending by the 6 date digits in the name. Is there a way to look at just these first 6 digits for the sort compare function?

I tried with just ba, but as the folder name lengths are dissimilar, the compare function doesn't return a useful sort.

//set new folder to get folder names and urls from
var parentFolderId = "ID Here";
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folders = parentFolder.getFolders();
var output = [];


 while (folders.hasNext()) {
  var folder = folders.next();
  output.push([folder.getUrl(),folder.getName()]); 
 }

output.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
    return 0;
}
else {
    return (a[1] < b[1]) ? 1 : -1;
}
}

A great thing about YYMMDD format is that alphabetic sorting is the same as chronological (as long as we stay within the same century; otherwise, you really should be using YYYYMMDD). So, the solution is to use simply

output.sort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM