Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs forEach and splice

Tags:

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

like image 652
chandu Avatar asked Jun 13 '14 10:06

chandu


2 Answers

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 image 137
James Allardice Avatar answered Sep 30 '22 00:09

James Allardice


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; 
like image 33
Tianzhen Lin Avatar answered Sep 29 '22 23:09

Tianzhen Lin