Filter array by date with google app script

2020-04-18 06:10发布

i've a google spreadsheet that is a 2 columns table that has on column A dates (i'm sure that are dates, and all the date functions works fine on all the column) and on column B text.

With google app script i've get all the values of the range with:

var sheet = SpreadsheetApp.openById(".........");
var ss = sheet.getSheetByName(".......");
var range =ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn());
var data =  range.getValues();

now i should have a 2d array with dates on data[0] and text on data[1]

i can filter the array on data[1] with:

var filter = data.filter(function (dataRow) {
return dataRow[1] == 'sometext';
});

what i need is to filter data[0] by some date value (like year, or month or a period)

i've tried:

var filter = data.filter(function (dataRow) {
return dataRow[0].getFullYear == 2016;
});

but any kind of date function gets me an error that states that is impossible to find the function (like getFullYear()) in the object.

What am i doing wrong?

Thank for any help

Best regards

3条回答
看我几分像从前
2楼-- · 2020-04-18 06:43

I've created a similar spreadsheet (first column with text, second with dates) and the following script:

function myFunction() {
  var sheet =  SpreadsheetApp.openById("…");
  var ss    = sheet.getSheetByName("testing");
  var range = ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn());
  var data  = range.getValues();

  var filtered = data.filter(function (row) {
    return row[1].getFullYear() === 2016;
  });

  Logger.log(filtered);
}

And it works as long as the second column is of Date type (Format→Number→Date). I get the error you've described if I change the type to Text. If there are no errors in your code (like .getFullYear instead of .getFullYear() as it's a function, not a property), I think the data (not the variable, but the spreadsheet's data) is not of Date type.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-04-18 06:58

The Date methods will work on a Date will work on a Date object, not text. What you have in the variable dataRow[1] is simply a string, not a Date object. Hence it doesn't have that method.

查看更多
Root(大扎)
4楼-- · 2020-04-18 07:04

Try this

var filtered = data.filter(function (row) {

  var d = new Date( row[1] ); // change text to Date object
  return  d.getFullYear() === 2016; // then compare

});
查看更多
登录 后发表回答