Reputation: 39
i am trying to remove an item from array but its not working i am using following code
vm.Continue = function () {
$scope.invalidList = [];
if (vm.errorexsist === true) {
var table = document.getElementById('errortabel');
for (var r = 0, n = table.rows.length; r < n; r++) {
if (r > 0) {
$scope.invalidList.push({
Error: table.rows[r].cells[0].val ,
FirstName: table.rows[r].cells[1].children[0].value,
Email: table.rows[r].cells[2].children[0].value,
PhoneNumber: table.rows[r].cells[3].children[0].value,
Location: table.rows[r].cells[4].children[0].value,
Department: table.rows[r].cells[5].children[0].value
});
}
}
var i = $scope.invalidList.length;
while (i--) {
if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {
$scope.invalidList.splice(i, 1);
}
}
}
};
the above code always removes item at zero while condition of if else does not meet.
Upvotes: 1
Views: 868
Reputation: 1844
Array.splice
will modify the length of an array, so you should iterate backwards through your array otherwise every time you call splice, the index and length of your for loop become obsolete.
var i = $scope.invalidList.length
while (i--) {
if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {
$scope.invalidList.splice(i, 1);
}
}
If you're looking to remove items from an array based on a condition, Array.filter
is designed for this exact purpose:
$scope.invalidList = $scope.invalidList.filter(item => !IsEmailValid(item.Email) || !IsPhoneNumValid(item.PhoneNumber))
Upvotes: 5