Last updated: Mar 6, 2024
Reading timeยท2 min
To check if a date is contained in an array:
find()
method to iterate over the array.find
method returns undefined
.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.
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.
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.
// ๐๏ธ 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.
You can learn more about the related topics by checking out the following tutorials: