3

I'm using MultipleDatePicker to select multiple date in year. I add a checkbox that when checked it will select all sunday in calendar.

I have a problem when unchecked it. It doesn't remove all selected sunday in calendar. I have compared by using getTime() as shown in the code below:

var selected = $scope.selectedDates;

for (var i = 0; i < $scope.selectedDates.length; i++) {
    var date1 = new Date(selected[i]).getTime();
    console.log('date1[' + i + '] = ' + date1 + ' ' + moment($scope.selectedDates[i], 'MM-DD-YYYY'));
    for (var j = 0; j < sundays.length; j++) {
        var date2 = new Date(sundays[j]).getTime();
        console.log('date2[' + j + '] = ' + date2 + ' ' + moment(sundays[j], 'MM-DD-YYYY'));
        if (date1 === date2) {
            selected.splice(i, 1);
            break;
        }
    }
}

Some are the same and some are not. What's wrong with the code?

Here is the plunker to show the problem.

2
  • while your problem got resolved already, I think you could have used .isSame for comparing momentJS objects.. current code looks cluttered a bit. Commented May 12, 2017 at 11:04
  • Yeah... Thanks for suggestions and improvements Commented May 12, 2017 at 11:13

3 Answers 3

3

The problem is that you removed item from array and your index i has increased in a loop so one item got skipped. To fix this, decrease i after each removal:

    // ...
    if (date1 === date2) {
        selected.splice(i, 1);
        i--;
        break;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

Little mistake, you forgot to decrement i, here is updated code.

for (var i = 0; i < $scope.selectedDates.length; i++) {
    var date1 = new Date(selected[i]).getTime();
    console.log('date1[' + i + '] = ' + date1 + ' ' + moment($scope.selectedDates[i], 'MM-DD-YYYY'));
    for (var j = 0; j < sundays.length; j++) {
        var date2 = new Date(sundays[j]).getTime();
        console.log('date2[' + j + '] = ' + date2 + ' ' + moment(sundays[j], 'MM-DD-YYYY'));
        if (date1 === date2) {
            selected.splice(i, 1);
            i--;
            break;
        }
    }
}

Comments

1

I think you forgot about decrement i, when you do splice

 if (date1 === date2) {
    selected.splice(i, 1);
    i = i - 1;
    break;
 }

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.