const regions = [
{
id: 1,
name: "Baden-Württemberg",
holidays: HOLIDAYS_BW,
},
{
id: 2,
name: "Bayern",
holidays: HOLIDAYS_BY,
},
]
const HOLIDAYS_BW = [
{ date: "01.01.2022", day: "Samstag" },
{ date: "06.01.2022", day: "Donnerstag" },
];
const HOLIDAYS_BY = [
{ date: "01.01.2022", day: "Samstag" },
{ date: "06.01.2022", day: "Donnerstag" },
];
How can I check wether the region and date the user picks is a holiday.
For instance I would like to check wether the region Bayern and the date 05.05.2022 is a holiday, the array shows all holidays
I tried this so far, but it does not seems to work
regions.find((region) => region.holidays.includes(date));
The date which I gave to the "query" is in this format
Tue Mar 22 2022 01:00:00 GMT+0100
That is an issue I think
You can try like so, finding if the region exists first (returns undefined if not), and then if the date is in the list.
return regions.find(r => r.name == region)?.holidays.some(h => h.date == date)
If you don't like the undefined and always want false, just add ?? false at the end.
return regions.find(r => r.name == region)?.holidays.some(h => h.date == date) ?? false
const HOLIDAYS_BW = [{
date: "01.01.2022",
day: "Samstag"
},
{
date: "06.01.2022",
day: "Donnerstag"
},
];
const HOLIDAYS_BY = [{
date: "01.01.2022",
day: "Samstag"
},
{
date: "06.01.2022",
day: "Donnerstag"
},
];
const regions = [{
id: 1,
name: "Baden-Württemberg",
holidays: HOLIDAYS_BW,
},
{
id: 2,
name: "Bayern",
holidays: HOLIDAYS_BY,
},
]
function formatDate(date) {
return `${('0' + (date.getDate())).slice(-2)}.${('0' + (date.getMonth())).slice(-2)}.${date.getFullYear()}`
}
function isHoliday(region, date) {
var formattedDate = formatDate(date);
return regions.find(r => r.name == region)?.holidays.some(h => h.date == formattedDate);
}
console.log(isHoliday('Bayern', new Date(2022, 01, 06))); // true
console.log(isHoliday('Baden-Württemberg', new Date(2022, 01, 01))); // true
console.log(isHoliday('Bayern', new Date())); // false
console.log(isHoliday('Hamburg', new Date(2022, 01, 06))); // undefined as Hamburg is not on the list
Turns out the input is a date, you can format it first with something like:
var formattedDate = `${('0' + (date.getDate())).slice(-2)}.${('0' + (date.getMonth())).slice(-2)}.${date.getFullYear()}`
and then use the string for the comparison.