Reputation: 258
I have an array of dates returned from an API. For example, I might have an array entitled validDates
that has all of the Mondays in September as their values. I would like to use the Material Datepicker filter to only allow date values in the array to be selected.
validDates = [
Mon Sep 02 2019 00:00:00 GMT-0500 (Central Daylight Time),
Mon Sep 09 2019 00:00:00 GMT-0500 (Central Daylight Time),
Mon Sep 16 2019 00:00:00 GMT-0500 (Central Daylight Time),
Mon Sep 23 2019 00:00:00 GMT-0500 (Central Daylight Time),
Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)
]
myFilter = ( d: Date ): boolean => {
let dateOpen: boolean;
for ( let x = 0; x < this.validDates.length; x++ ) {
dateOpen = d.toString() === this.validDates[ x ].toString();
}
return dateOpen;
}
The issue is it only returns the last date (Mon Sep 30 2019 00:00:00 GMT-0500 (Central Daylight Time)) as true
so that only the 30th becomes selectable. I want each of the dates in the array to be selectable.
How can I return true
for each value in the array?
Upvotes: 1
Views: 1843
Reputation: 11
Finally I found correct solution:
// The array of days of week to be available
const arr = [0, 3, 6];
this.expressSenderDate = (d: Date): boolean => {
const day = d.getDay();
// tslint:disable-next-line:align
return arr.indexOf(day) !== -1;
};
Upvotes: 0
Reputation: 24104
To only allow dates within an array, the myFilter
method may be defined as follows.
myFilter = (d: Date): boolean => {
// Only allow dates in `validDates`.
return this.validDates.findIndex( (valid_date) => d.getTime() === valid_date.getTime()) > -1
}
See Stackblitz Demo
To ignore the time component of the Date
, see:
Comparing date part only without comparing time in JavaScript
Upvotes: 1