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?
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?
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