且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何识别Google云端硬盘文件夹中的最新文件

更新时间:2023-02-14 14:11:23

您离解决方案并不遥远......我尝试使用稍微不同的方法:我将所有日期和ID存储在二维数组中,我对数组进行排序,并在第二维中检索第一个元素(排序后)以返回文件ID。



代码:

pre $ function listLatestFile(){
var folder = DriveApp.getFoldersByName( GmailAttachments);
var files = DriveApp.getFilesByName('mrp_out.xlsx');
var result = [];
while(files.hasNext()){
var file = files.next();
result.push([file.getDateCreated(),file.getId()]);
}
Logger.log(result);
var id = result.sort()[0] [1];
Logger.log(id);
return id; //返回最近的文件ID
};

编辑:如果您想对排序方法有更多的控制权,您可以使用更复杂的排序方法,如下所示:

  ... //同上
结果.sort(function(x,y){
var xp = x [0]; //获取内部数组中的第一个元素
var yp = y [0];
return xp == yp?0:xp< yp?-1:1; //选择排序顺序
});
var id = result [0] [1];
Logger.log(id);
return id;
};


I have a folder in Google drive in to which files are regularly dumped from a reporting tool. The files are in .xls format. They all have the same name and I want to identify the most recent file so that I can import the data in to a Google sheet.

As you will be able to tell from the below I am new to Google Apps script. I have been trying to catch the various files from the file iterator into an array to run a Math.max function on the result to end up with just one value. Of course, once I have identified the newest date I also need to return the fileID associated with - but I haven't got that far yet. I am probably heading in the completely wrong direction so any tips/guidance would be greatly appreciated.

function listLatestFile(id) {
var folder = DriveApp.getFoldersByName("GmailAttachments");
var files = DriveApp.getFilesByName('mrp_out.xlsx');
while (files.hasNext()) {
 var file = files.next();
 var date = (1 - file.getDateCreated());
 var datediff = new Array(date);
 var datelast = Math.max(datediff);
 Logger.log(datelast);
 } 
//Logger.log(date);
};

You were not very far from the solution... I tried using a slightly different approach : I store all dates and IDs in an 2D array, I sort the array and retrieve the first element (after sorting) in the 2cond dimension to return the file ID.

code :

function listLatestFile() {
  var folder = DriveApp.getFoldersByName("GmailAttachments");
  var files = DriveApp.getFilesByName('mrp_out.xlsx');
  var result = [];
  while (files.hasNext()) {
    var file = files.next();
    result.push([file.getDateCreated(),file.getId()]);
 } 
  Logger.log(result);
  var id = result.sort()[0][1];
  Logger.log(id);
  return id;// return most recent file ID
};

EDIT : if you want to have more control on the sorting method, you can use a more "sophisticated" sort method like below :

   ...// same as above
  result.sort(function(x,y){
    var xp = x[0];// get first element in inner array
    var yp = y[0];
    return xp == yp ? 0 : xp < yp ? -1 : 1;// choose the sort order
  });    
  var id = result[0][1];
  Logger.log(id);
  return id;
};