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" }, ];¿Cómo puedo comprobar si la región y la fecha que elige el usuario es un día festivo?
Por ejemplo, me gustaría verificar si la región Bayern y la fecha 05.05.2022 es un día festivo, la matriz muestra todos los días festivos.
Intenté esto hasta ahora, pero no parece funcionar.
regions.find((region) => region.holidays.includes(date));La fecha que le di a la "consulta" está en este formato
Tue Mar 22 2022 01:00:00 GMT+0100eso es un tema creo
Puede intentar así, encontrando si la región existe primero (devuelve undefined si no), y luego si la fecha está en la lista.
return regions.find(r => r.name == region)?.holidays.some(h => h.date == date) Si no te gusta lo undefined y siempre quieres falso, solo agrega ?? false al final.
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 listResulta que la entrada es una fecha, puede formatearla primero con algo como:
var formattedDate = `${('0' + (date.getDate())).slice(-2)}.${('0' + (date.getMonth())).slice(-2)}.${date.getFullYear()}`y luego use la cadena para la comparación.