Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array containts Date

Tags:

javascript

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?

like image 755
Stophface Avatar asked Jan 28 '26 04:01

Stophface


1 Answers

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

like image 87
Nicholas Tower Avatar answered Jan 29 '26 19:01

Nicholas Tower