I have a date range in a array say 11th may 2023 to 4July 2023 [11/5/2023,12/5/2023,13/5/2023, ..... 4/7/2023] .
Now I want a array which contain these days as a week where week starts with Monday and ends on Sunday in a format like this [[11/5/2023,12/5/2023,13/5/2023,14/5/2023],[15/5/2023,16/5/2023 ....] , ..[3/7/2023,4/7/2023]]
How can I achieve this ?
>Solution :
You can iterate the array with Array::reduce() and create child arrays after the date is Sunday (dt.getDay() === 0):
// preparing the range array
const start = new Date('2023-05-11T00:00:00');
const stop = new Date('2023-07-04T00:00:00');
const arr = [];
while(start<=stop){
arr.push(new Date(start));
start.setDate(start.getDate() + 1);
}
// the needed code starts here
const result = arr.reduce(({idx, result}, dt) => {
(result[idx] ??= []).push(dt);
dt.getDay() || idx++;
return {idx, result};
}, {idx: 0, result: []}).result
console.log(JSON.stringify(result,(_,v) => typeof v === 'string' ? new Date(v).toDateString(): v,4));