Check if a Date is contained in an Array using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 26, 2022

banner

Check out my new book

Check if a Date is contained in an Array using JavaScript #

To check if a date is contained in an array:

  1. Use the find() method to iterate over the array.
  2. On each iteration, check if the date's timestamp is equal to a specific value.
  3. If the date is not found, the find method returns undefined.
index.js
const arr = [ new Date('2022-03-11'), new Date('2022-04-24'), new Date('2022-09-24'), ]; const date = arr.find( date => date.getTime() === new Date('2022-04-24').getTime(), ); console.log(date); // 👉️ Sun Apr 24 2022

The function we passed to the Array.find method gets called with each element (date) in the array until it returns a truthy value or iterates over all elements.

If the function returns a truthy value, the corresponding array element is returned.

On the other hand, if the condition is never met, the find method returns undefined.

The example checks if a specific date (including the time) is contained in an array.

If you only want to check if the date is in the array, ignoring the time, use the toDateString method when comparing.

index.js
const arr = [ new Date('2022-03-11'), new Date('2022-04-24'), new Date('2022-09-24'), ]; const date = arr.find( date => date.toDateString() === new Date('2022-04-24T09:35:31.820Z').toDateString(), ); console.log(date); // 👉️ Sun Apr 24 2022

The toDateString method returns the date portion of a Date object in human-readable form.

index.js
// 👇️ Wed Jan 26 2022 console.log(new Date().toDateString());

If the method returns the same string for the two dates, then the dates have the same year, month and day values.

This approach enables us to compare the dates without taking the time into consideration.
Use the search field on my Home Page to filter through my more than 3,000 articles.