'find duplicate files in one folder and removing the oldest one? (Google Script)

I have a script that backup my google sheets into a single folder, what I’m trying to do is creating a new script that can search this backup folder for file duplicates and deletes the old one and only keep the new backup.

I’d really appreciate your help

I found some scripts online that can delete the newer duplicate but what I need is to delete the older and keep the newer backup



Solution 1:[1]

Keep newest file in folder

function keepNewest()  {
  const folder = DriveApp.getFolderById("WlMK1uJlbcbmol7UcDV2X1");
  const files = folder.getFiles();
  let keep = [];
  while(files.hasNext()) {
    keep.push(files.next());
  }
  keep.sort((a,b) => {
    let va = new Date(a.getDateCreated()).valueOf();
    let vb = new Date(b.getDateCreated()).valueOf();
    return vb - va;
  })
  keep.forEach((f,i) => {
    if(i>0) {
      Drive.Files.remove(f.getId());
    }
  });
}

Drive API must be enabled

Keep newest file of each name in a folder

   function keepNewestFilesOfEachNameInAFolder() {
  const folder = DriveApp.getFolderById("WlMK1uJlbcbmol7UcDV2X1");
  const files = folder.getFiles();
  let fO = { pA: [] };
  let keep = [];
  while (files.hasNext()) {
    let file = files.next();
    let n = file.getName();
    //Organize file info in fO
    if (!fO.hasOwnProperty(n)) {
      fO[n] = [];
      fO[n].push(file);
      fO.pA.push(n);
    } else {
      fO[n].push(file);
    }
  }
  //Sort each group with same name
  fO.pA.forEach(n => {
    fO[n].sort((a, b) => {
      let va = new Date(a.getDateCreated()).valueOf();
      let vb = new Date(b.getDateCreated()).valueOf();
      return vb - va;
    });
    //Keep the newest one and delete the rest
    fO[n].forEach((f, i) => {
      if (i > 0) {
        Drive.Files.remove(f.getId());
      }
    });
  });
}

Drive API must be enabled Tested both versions

If you wish to test on your system here's a script to create text files

function createFiles() {
  const folder = DriveApp.getFolderById("WlMK1uJlbcbmol7UcDV2X1");
  const names = ["A","B","C"]
  names.forEach((n,i) => {
    [...Array.from(new Array(3).keys(),x => x + 1)].forEach(idx => {
      folder.createFile(n,`This is text file name ${n} file number ${idx}.`,MimeType.PLAIN_TEXT);
    });
  });
}

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