2

How do I check if an array contains a date?

const dateArr = [new Date("12-12-2012"), new Date("06-06-2006"), new Date("01-01-2001")]

dateArr.includes(new Date("12-12-2012"))

false

Why is that?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • `new Date()` is a new reference **value**. Try `var dateArr = [new Date("12-12-2012").getTime(), new Date("06-06-2006").getTime(), new Date("01-01-2001").getTime()]; dateArr.includes(new Date("12-12-2012").getTime())` – gurvinder372 Oct 26 '17 at 14:19
  • 1
    `new Date("12-12-2012") == new Date("12-12-2012")` **returns `false`** - these items are not the same, and thus `includes` will ignore them. You can get some more information here: [Why are two identical objects not equal to each other?](https://stackoverflow.com/questions/11704971/why-are-two-identical-objects-not-equal-to-each-other) – Tyler Roper Oct 26 '17 at 14:22

1 Answers1

5

Every time you call new Date("12-12-2012"), you create a new object. These objects happen to have the same value inside them, but they're different objects. dateArray.includes will check reference identity, and will fail the check because they are different objects.

If you want to check whether there's an element that matches some condition, you can use array.find, and specify what should count as "equal":

const dateArr = [new Date(1), new Date(2), new Date(3)]

const testDate = new Date(1);
const match = dateArr.find(d => d.getTime() === testDate.getTime())
const hasMatch = !!match; // convert to boolean
console.log(hasMatch);

PS, you should avoid constructing dates with datestrings, since there are inconsistencies across browsers. For example, on firefox, new Date("12-12-2012") produces an invalid date

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98