'How to sort files according to date created with google apps script?

I'm looking to sort the files in a folder by the date they were created or last modified. I'm loading the contents of a folder in google drive with the following code:

var folder = DriveApp.getFolderById(folderID);
var contents = folder.getFiles();
data = file.getId();
var image = DriveApp.getFileById(data);

My understanding is that contents above is an array containing a list of file IDs in the drive. Is it possible to sort contents by date created/modified before proceeding to the next step?



Solution 1:[1]

### Sorting an array of files by datecreated
function myfunction() {
    var folder = DriveApp.getFolderById(folderID);
    var contents = folder.getFiles();
    let arr = [];
    while (contents.hasNext()) {
        let file = contents.next();
        arr.push(file)
    }
    //sort arr by dateCreated
    arr.sort((a, b) => {
        let vA = new Date(a.getDateCreated()).valueOf();
        let vB = new Date(b.getDateCreated()).valueOf();
        return vA-vB
    });
    //the rest of your code makes no sense. 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Callum