Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array of dates grouped by a week as a subarray?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading