I have an array like this:
$scope.emails = [
{\"key\":\"Work\",\"value\":\"user@domine.com\"},
{\"key\":\"\",\"value\":\"\"},
{\"key\":\"Work\",\"value\":
indexOf
returns -1
when it doesn't find an item.
A way to remove an item, and to avoid removing the last one when not found, is:
var index = $scope.items.indexOf($scope.oldItem);
if (index != -1) {
$scope.items.splice(index, 1);
}
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.
According to the docs, the iterator function allows a third parameter which is the collection which is being iterated. Splicing that collection instead of $scope.emails
will remove the expected obejct.
angular.forEach($scope.emails, function(email, index, obj){
if(email.value ===""){
obj.splice(index, 1);
}
});
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;
I haven't tried this with AngularJs, but with Angular 4 a similar way of this works pretty well.
angular.forEach($scope.emails, function(email){
if(email.value ===""){
$scope.emails.splice($scope.emails.indexOf(email), 1);
}
});
Angular 4 version:
this.emailArray.forEach(email => {
if (email.value == "") {
this.emailArray.splice(this.emailArray.indexOf(email),1);
}
});
describe('Foreach Splice', function () {
it('splicing', function () {
var elements = [
{name: "Kelly", age: 16},
{name: "", age: 17},
{name: "Becky", age: 18},
{name: "", age: 18},
{name: "Sarah", age: 19},
{name: "", age: 20},
{name: "", age: 22},
{name: "Mareck", age: 21},
{name: "", age: 21},
{name: "Mareck", age: 21}
];
removeEmptyEntry(elements);
console.log(elements);
});
function removeEmptyEntry(elements) {
elements.forEach(function (element, index) {
if (!element.name) {
elements.splice(index, 1);
removeEmptyEntry(elements);
}
});
}
});