Laiacy
Laiacy

Reputation: 1600

When pushing values into an array from a while loop that is inside a `for` loop, it overwrites the previous elements in the array

When I push values into an array from a while loop inside that's for loop it overwrites the previous elements inside the array.

        var startDate = new Date(theoreticalData[0].UpdateDateMDY);
        var newDate = startDate;
        var daysDif = 0;
        var daysArray = [startDate];
        for ( var i= 1; i<theoreticalData.length; i++ ) {                
            var OldCycle = parseInt(theoreticalData[i].OldCycle);
            daysDif = theoreticalData[i].DaysDifference;
            while (daysDif > OldCycle ) {
                nextDate = this.sumDays(nextDate , OldCycle);
                daysArray.push(nextDate);
                daysDif = daysDif - OldCycle;
            } 
            nextDate = this.sumDays(nextDate , daysDif);
            daysArray.push(nextDate);
        }

Upvotes: 1

Views: 1743

Answers (1)

gurvinder372
gurvinder372

Reputation: 68373

When I push values inside a while loop inside a for loop it overwrites the previous elements inside the array.

Because you are updating the same object everytime and pushing it to the array,

change this line

nextDate = this.sumDays(nextDate , OldCycle);

to

nextDate = new Date(this.sumDays(nextDate , OldCycle).getTime());

This will create a new Date object everytime.

Upvotes: 1

Related Questions