Scenario
We have a text input="11/25/2014"
. We want to see whether the input matches any of the dates in the array:
const dates = [new Date(2014, 11, 25), new Date(2014, 11, 24), new Date(2014, 11, 25)];
Approach
First we’ll check whether the date is valid with !isNaN(new Date(input).getTime()
.
Then we will find all the dates that mach using Array.filter
:
let result = []if (!isNaN(new Date(input).getTime())) {
result = dates.filter(date=> {
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
const dateString = `${monthIndex}/${day}/${year}`;
return dateString.includes(input);
});
}
console.log("The dates that match are: ", result);
console.log("Two dates match: ", result.length == 2);