0
votes

In a google sheet I have a self populating list of twitter tweets and I'm trying to filter out all tweets from the previous day.

I keep getting an error:

"Cannot read property 'length' of undefined"

Error is on the last line of the code

targetSheet.getRange(1,1, filteredData.length, filteredData[0].length).setValues(filteredData);

function FilterByDate() {
  var sSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = sSheet.getSheetByName("Tweetz2");
  var targetSheet = sSheet.getSheetByName("Tweetz3");

 var TodaysDate = new Date();
 TodaysDate.setHours(00, 00, 00, 001)
 var startDate =  new Date(TodaysDate.getTime() - (29 * 60 * 60 * 1000) + (10)); // 24hr + 6hr time zone diff 
 var endDate =  new Date(TodaysDate.getTime() - (5 * 60 * 60 * 1000) + (10)); // 6hr time zone diff

  var data  = sourceSheet.getDataRange().getValues();
  var filteredData = data.filter(dataRow => (dataRow[1] > startDate && dataRow[1] < endDate));
   targetSheet.getRange(1,1, filteredData.length, filteredData[0].length).setValues(filteredData);
}

I use this same code to filter different data on another sheet and it works fine.

This is the first time I've tried to use it to filter by date.

Date Time is column A on the sourceSheet.

I don't understand why it dosent work here. Please help!

3
You could debug down to the last line and see what filteredData looks like. - Cooper
I used a logger to display data and filtered data. Data shows fine. filtereddata no value - ABB1987
Check that every cells are the same format - Waxim Corp

3 Answers

0
votes

Try changing this var filteredData = data.filter(dataRow => (dataRow[1] == TargetDate)); to this: var filteredData = data.filter(dataRow => (new Date(dataRow[1]).valueOf() == TargetDate));

0
votes

Replace

targetSheet.getRange(1,1, filteredData.length, filteredData[0].length).setValues(filteredData);

by

if(filteredData.length > 0) targetSheet.getRange(1,1, filteredData.length, filteredData[0].length).setValues(filteredData);

The reported errors is very likely that occurs because filteredData has 0 elements.

0
votes

Issue:

According to what you said, sheet dates are in column A:

Date Time is column A on the sourceSheet.

And you're comparing your dates to the values in column B, since arrays are 0-indexed and you're using dataRow[1].

Because of this, you are comparing a date with something that is not a date. Therefore, no element in data matches the filter conditions, and so filteredData is empty.

Solution:

Therefore, you should replace this:

var filteredData = data.filter(dataRow => (dataRow[1] > startDate && dataRow[1] < endDate));

With this:

var filteredData = data.filter(dataRow => (dataRow[0] > startDate && dataRow[0] < endDate));

Also, checking whether filteredData has any elements might be appropriate too, as Rubén mentioned: if(filteredData.length > 0) ...

Reference: