Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  197] [ 4]  / answers: 1 / hits: 58844  / 10 Years ago, fri, june 13, 2014, 12:00:00

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


More From » angularjs

 Answers
17

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.


[#70588] Wednesday, June 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;