0

I have two variables, one holds a hard coded date and the other has an array with a single value (for testing) . the value in the array matches the hard coded value yet I get a return of -1(no match).

var cur_date = new Date('7/31/2018') ;
var last_row_cur = sales_sheet.getRange(1,1,20,10).getCell(index+1,10).getValue();        
var date_array = sales_sheet.getRange(index,9,last_row_cur,1).getValues()[1]; 
var date_index = date_array.map(function(e) {return e[0]}).indexOf(cur_date);

the log results: Cur_date = Tue Jul 31 00:00:00 GMT-05:00 2018

var_date_array = [Tue Jul 31 00:00:00 GMT-05:00 2018]

var_date_index = -1

I was hoping var_date_index would return 0 as is the only result in the array and the dates match. I am guessing it has something to do with the [] but I am new to this so not sure. TIA

datafarmer
  • 43
  • 1
  • 1
  • 9

1 Answers1

0

I just tested your code and the outcome is that

 Logger.log(date_array)

returns

“Tue Jul 31 00:00:00 GMT+02:00 2018”

while

 Logger.log(date_array.map(function(e) {return e[0]}))

returns

“T”

date_array.map(function(e) {return e[0]})

does not give you your array element

sales_sheet.getRange(index,9,last_row_cur,1).getValues()[0],

since the mapping function is trying to retrieve an array element from an array. But in your case

date_array 

is an array element. You are actually trying to access an element of an element (and not of an array), this is what gives you the error.

If you just change your last line from

var date_index = date_array.map(function(e) {return e[0]}).indexOf(cur_date);

to

var date_index = date_array.indexOf(cur_date);

it will work.

However, if you want to use the mapping, then you should define date_array as:

var date_array = sales_sheet.getRange(index,9,last_row_cur,1).getValues();
Community
  • 1
  • 1
ziganotschka
  • 25,866
  • 2
  • 16
  • 33
  • 1
    `indexOf` uses strict equality comparison. Objects (date) compared using strict equality `===` will always be false. – TheMaster Jun 22 '19 at 04:29
  • This is also an important issue. `Utilities.formatDate(cur_date, timeZone, format)` can be used to convert the date to a string - to make it comparable. – ziganotschka Jun 22 '19 at 18:33