Question:
With the following code, I want to push an array inside theweeks
array if i
is <=
to the value of each element in that array.Any help would be greatly appreciated.
Answer:
Create a new array inside of theif (i % 7 === 0){
statement. That array is going to be created for every week and is going to hold your days.Now start the second loop by subtracting
6
from the current value of i
. i
will always be a multitude of 7. So by subtracting 6 you get the first day in that week. Store that result in j
.Then for the evaluation part of the loop, check if
j
is equal or lower than i
, we never want to go higher than the last day in the current week. Also check if j
is equal or lower than numberOfDays
. You don’t want to add more days than you indicated.Add each day to the days array. Then after the loop add the days array to
daysInWeek
. Now you got this nested array structure.const weeks = [];
const daysInWeek = [];
numberOfDays = 35;
for (let i = 1; i <= numberOfDays; i ++) { if (i % 7 === 0){ weeks.push(i) const days = []; for (let j = i - 6; j <= i && j <= numberOfDays; j++) { days.push(j); } daysInWeek.push(days); } } console.log(daysInWeek);[/code]
If you have better answer, please add a comment about this, thank you!