BDD
BDD

Reputation: 715

JavaScript: Storing dates in array in for loop

I'm trying to loop through to check if the first date is less than the second date. If it is, I want to store the value in an array, add 1 day to the first date, then go back through the process. I think that's what I've written, but I'm not sure why it's not working. When I console out any any of the array values, it's always the last date that appears and I can't get any of the other values to store. After stepping through it with Firebug, it looks like they are being overwritten. I'm using moment.js to get the dates.

var counter = 1;
var arr = [];
var i = firstDate.toDate();

for(counter; firstDate < secondDate; counter++){
        arr[i]=firstDate.toDate();
        firstDate.add(1, "day");
    }

console.log(arr[2]);

Any help would be greatly appreciated!

Upvotes: 0

Views: 683

Answers (2)

James Hunt
James Hunt

Reputation: 2528

The variable i never changes once set, so you're constantly writing to the same index.

Also, your counter variable is never used. Consider using your counter variable as the index as it will be unique for each iteration. Alternatively, if you want to continue using the date as an index, add the line i = firstDate.toDate(); to the top of your for loop.

For the latter, your loop should look like this:

var counter = 1;
var arr = [];
var i = firstDate.toDate();

for(counter; firstDate < secondDate; counter++){
    i = firstDate.toDate();
    arr[i]=firstDate.toDate();
    console.log(firstDate.toDate());
    firstDate.add(1, "day");
}
console.log(arr[2]);

I suggest adding a console log to your loop (as above) if you're having problems, to see which dates are being added as they are being added.

Upvotes: 2

chazsolo
chazsolo

Reputation: 8429

Since the difference between first and second date is unknown beforehand you could use a while loop instead

while( firstDate.isBefore(secondDate) ) {
    arr.push(firstDate.toDate());
    firstDate.add(1, 'day');
}

Upvotes: 0

Related Questions