Check if a Date is contained in an Array using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

# 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

check if date is contained in array

The code for this article is available on GitHub

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.

# Check if a date is in an array, ignoring the time

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

check if date is in array ignoring the time

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev