I have an array like this:
$scope.emails = [ {"key":"Work","value":"[email protected]"}, {"key":"","value":""}, {"key":"Work","value":"[email protected]"} {"key":"","value":""}];
So, I want to remove empty emails but angular forEach
method removing only one object that is last object why???.
js code
angular.forEach($scope.emails, function(email, index){ if(email.value ===""){ $scope.emails.splice(index, 1); } });
where I am doing wrong
JS Bin
The problem is that you remove elements from the array during the loop so later items are at different indices. You need to loop backwards instead:
for (var i = $scope.emails.length - 1; i >= 0; i--) { if (!$scope.emails[i].value) { $scope.emails.splice(i, 1); } }
Here's an updated example.
Like others have pointed out, the culprit of the code is the array got removed. To get around with angular.forEach, you can try the additive/assignment approach:
var filteredEmails = []; angular.forEach($scope.emails, function(email, index){ if(email.value !==""){ filteredEmails.push(email); } }); $scope.emails = filteredEmails;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With