-1

I have an array of date object and want to check if supplied date exists in the array by array.indexOf method but it's always returning -1 (not found). Although date exists in the array.

Please have a look at attachment.

availableDates[62] and Date have the same value when I print in the console but the condition is returning false.

Sujal Patel
  • 2,444
  • 1
  • 19
  • 38
Aamir Nakhwa
  • 393
  • 1
  • 12
  • 5
    Show your code. Not a screenshot from your console, but runnable code.... – random_user_name Jun 10 '19 at 13:44
  • All we can do is guess if we have a photo of the output from your code. – Chris Barr Jun 10 '19 at 13:45
  • 3
    You need to compare dates using the `getTime()` method. Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – jeffjenx Jun 10 '19 at 13:45
  • A `new Date` will not equal another using `==`, you need to compare some value of the date. – chazsolo Jun 10 '19 at 13:47
  • @Quantastical I want to check date in array of Date. – Aamir Nakhwa Jun 10 '19 at 13:49
  • @AamirNakhwa the problem is not how you are searching the array, the problem is how you are deciding whether or not two dates are equivalent. Dates are objects, and object equality is by *reference*: `new Date(2019, 0, 1) !== new Date(2019, 0, 1)`. – Jared Smith Jun 10 '19 at 13:56
  • Something like this would do it: `const hasDate = ( date, dates, test = date.valueOf() ) => !! (dates .find (d => d.valueOf() == test) )`. – Scott Sauyet Jun 10 '19 at 14:08

1 Answers1

0

You can use the Date​.prototype​.get​Time() to get the Unix time stamp to compare with

const arr = [new Date(), new Date(), new Date(), new Date(), new Date(), new Date()];
const selectedDate = arr[1]; // choose any date here, I use this as example.

console.log(arr.some(date => date.getTime() === selectedDate.getTime())); // true
mottosson
  • 3,283
  • 4
  • 35
  • 73
  • 1
    You're changing what OP was doing. OP was comparing two completely different date objects (one in an array, one created outside the array). You're comparing an array item with itself. – jeffjenx Jun 10 '19 at 13:55
  • Updated my example. – mottosson Jun 10 '19 at 14:01