Delete date array using another date array

I am using MultipleDatePicker to select multiple dates in a year. I am adding a checkbox that, when checked, will select all Sunday in the calendar.

I have a problem where it is not installed. It does not delete all selected Sundays in the calendar. I compared 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 of them are the same and some are not. What's wrong with the code?

A plunker is shown here to show the problem.

+3


source to share


3 answers


The problem is that you removed an element from the array and your index i

increased in a loop so that one element was skipped. To fix this, minify i

after each removal:



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

      

+3


source


Little mistake, you forgot the decrement i

, here is the 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;
        }
    }
}

      

+3


source


I think you forgot the decree i

when you dosplice

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

      

+1


source







All Articles