My task involves iterating through multiple date intervals, like:
- 09/06/2023 - 15/06/2023
- 28/05/2023 - 02/06/2023
- 17/06/2023 - 18/06/2023
- 29/06/203 - 04/07/2023 ...and so on
I want to extract the day numbers for a specific month only, for example, June (06).
The expected output should be an array like this:
var june = [09,10,11,12,13,14,15,01,02,17,18,29,30];
To achieve this, I followed these steps:
a. Queried in PHP to retrieve departing, returning dates, and number of date intervals as string arrays (not Date objects)
b. Created JavaScript arrays for departing, returning dates: var departure, var rback, var number
c. Defined an empty array 'days':
var days=[];
d. Looped through all date intervals to obtain dates between the intervals
function enumerateDaysBetweenDates(startDate, endDate) {
startDate = moment(startDate,"DD/MM/YYYY");
endDate = moment(endDate,"DD/MM/YYYY");
var now = startDate, dates = [];
while (now.isBefore(endDate) || now.isSame(endDate)) {
dates.push(now.format("DD/MM/YYYY"));
now.add(1, 'days');
}
return dates;
};
for (i = 0; i < number.length; i++) {
var mdepart=departure[i];
var mrback=rback[i];
days.push(enumerateDaysBetweenDates(mdepart,mrback));
};
Next step is to filter out dates that are not in June:
function checkd(num) {
return num.includes("/06/");
};
var june=days.filter(checkd);
The issue I encountered is "days.filter is not a function" error...
If I try using
var june = Object.values(days).filter(checkd);
, it results in an empty array...
I'm unsure about the problem. Is it because the initial date array elements were defined as strings and now they are treated as dates with moment.js?
Complete code snippet:
var days=[];
var number=[1,2,3,4];
var departure=[09/06/2023,28/05/2023, 17/06/2023, 29/06/2023];
var rback=[15/06/2023,02/06/2023,18/06/2023,04/07/2023];
function enumerateDaysBetweenDates(startDate, endDate) {
startDate = moment(startDate,"DD/MM/YYYY");
endDate = moment(endDate,"DD/MM/YYYY");
var now = startDate, dates = [];
while (now.isBefore(endDate) || now.isSame(endDate)) {
dates.push(now.format("DD/MM/YYYY"));
now.add(1, 'days');
}
return dates;
};
for (i = 0; i < number.length; i++) {
var mdepart=departure[i];
var mrback=rback[i];
days.push(enumerateDaysBetweenDates(mdepart,mrback));
};
//Now I need to filter all dates that are not in June:
function checkd(num) {
return num.includes("/06/");
};
var june=days.filter(checkd);
//Error days.filter or empty array....
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>