-1

Is there a way to get all the dates of the current week? For example today is 11/22/2021. So I need an array of ["11/21/2021", "11/22/20201", "11/23/2021", "11/24/2021", "11/25/2021", "11/26/2021", "11/27/2021"]

Also this array needs to be consistent for the entire week until it is Sunday, then it will create a new array.

Tim Taylor
  • 81
  • 1
  • 7
  • Does this answer your question? [How to get the Days b/w current week in moment.js](https://stackoverflow.com/questions/34871998/how-to-get-the-days-b-w-current-week-in-moment-js) – Heartbit Nov 23 '21 at 00:28
  • 2
    Does this answer your question? [JS- Get days of the week](https://stackoverflow.com/questions/43008354/js-get-days-of-the-week) – evolutionxbox Nov 23 '21 at 00:29

1 Answers1

3

Something like that ?

Array.from(Array(7).keys()).map((idx) => {const d = new Date(); d.setDate(d.getDate() - d.getDay() + idx); return d; });

Some explanation, Array(7) will create an empty array with 7 entries.

Array(7).keys() will return an iterator with the array keys.

Array.from(Array(7).keys()) will transform the iterator into a new array with 7 entries containing integers (aka [0, 1, 2, 3, 4, 5, 6])

d.getDate() - d.getDay() + idx, we take the current day (23), remove the day of week (0 for Sunday, 2 for Tuesday... Basically we calculate the last Sunday date) et add number of days to have every date in the week.

Joel
  • 1,187
  • 1
  • 6
  • 15