I have an input array of month-year strings of disabled months selected by the user:
disabledDates = [
"2020-01",
"2014-07",
"2020-03",
"2011-08"
"2011-10"
]
(But it can be much longer)
The user is displayed a calendar with years and months only - he can select an year using a dropdown. For each year I want to grey out the month cubes that are disabled in the given array.
Right now my solution does not seem too performant: I convert each string to date and get the year using new Date().getFullYear()
every time a user selects an year and check for every date if it matches the current selected year and if so I use getMonth()
to grey out matching months:
let disabledMonths = [];
let dateObject;
disabledDates.forEach(function(date) {
dateObject = new Date(date);
if (dateObject.getFullYear() === currentSelectedYear) {
disabledMonths.push(dateObject.getMonth());
}
}
for (let i = 0; i < 12; i++) {
if (disabledMonths.includes(i)) {
calendarElement.innerHtml += `<div class="disabled_month"...>`;
} else {
calendarElement.innerHtml += `<div ...>`;
}
}
But I think it does unnecessary iterations every time. Maybe there's a better way, such as "grouping" all the dates by years, then only if there's a matching year in this group - get the months and grey them out. But is something like that possible?
( Also, I want to also add the same feature but when displaying days as well, so it can be an array of full dates:
disabledDates = [
"2020-01-01",
"2014-07-12",
"2020-03-30",
"2011-08-11"
"2011-10-05"
]
so that might add more iterations )