Home > Enterprise >  for loop replacing all previous items in array
for loop replacing all previous items in array

Time:03-23

I'm trying to create a series of dates based on an array of weeks.

There are four weeks with 5 days each, each week being an object containing the weeknumber and an array of 5 days - the days being objects that contain the day and the date.

weeks[0].days[0].day would return Monday, for example.

I use LuxonJS to generate the date based on the weeknumber and day in the week using the function generateDate(weekNr, dayNr).

To fill the date value in the weekday items, I've tried the following:

for(x = 0; x <= weeks.length; x  ){
   for(y = 0; y <= weeks[x].days.length; y  ){
      weeks[x].days[y]['date'] = generateDate(weeks[x].weekNr, y)
   }
}

However, for some reason the days every week now get filled with the dates of the last week, so weeks[0].days[4].date would return the exact same date as weeks[3].days[4].date. In other words - apart from the week number, the 4 weeks become identical.

If I log the dates in the for-loop, they all appear correctly, so it seems they get replaced each time the first for-loop repeats. Does anyone know what I'm doing wrong?

CodePudding user response:

This behaviour is probably related to how you built the original weeks array. It looks like you assigned the same object to all four entries in weeks, instead of creating a new object for each entry.

Then when you run that nested loop, you will be mutating the same object for each iteration of the outer loop. So make sure to create a new object each time you assign (or push) an object to the weeks array.


As a side note, here is how I would do it in vanilla JavaScript:

function getWeekDays(year, weekNr) {
    let dt = new Date(year, 0, 4); // 4 January is always in week #1
    // Get Sunday before the start of the week
    dt.setDate(dt.getDate() - (dt.getDay() || 7) - 7   weekNr * 7);
    return {
        weekNr,
        days: Array.from({length: 5}, () => {
            dt.setDate(dt.getDate()   1); // Increment date
            return { 
                day: dt.toLocaleDateString("en", { weekday: 'long'}), 
                date: dt.toLocaleDateString("en-SE")
            };
        })
    };
}

function getMonthDays(year, firstWeek, numWeeks) {
    return Array.from({length: numWeeks}, () => getWeekDays(year, firstWeek  ));
}

// Example creation of the weeks array
let weeks = getMonthDays(2022, 9, 4);
console.log(weeks);

  • Related