0

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So I tried moving i = firstDate.toDate() into my loop, but I still get the same outcome. Is there something else I need to adjust as well?
See my edit, using that for loop, what gets printed to the console?
The console.log(firstDate.toDate()); inside the for loop consoles out each day of the month, but the console.log(arr[2]); consoles out undefined
0

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.