Asim Zaidi
Asim Zaidi

Reputation: 28284

javascript array pop without another foreach loop

my test array has multiple objects in them that I want to iterate over and if a condition is not met I want to pop it from main array. I am using foreach loop. so

so I am using a foreach loop and doing

$.foreach(test, function(idx, val){
  if(true){
         test.splice(idx, 1);
  }
});

problem is that it doesn’t work as if there are two objects for example, as shown below, it will reindex the array after the first iteration and then the second iteration which will be idx 1, will not be able to do test.spice(1,1) since index 1 does not exist in the array anymore.

Now I know that I can create a temporary place holder and the indexes there and then run another foreach but thats what I am trying to avoid. Any ideas will be appreciated

[
                     email: “testemail@emailcom”
                     firstName: “Test"
]
[
                     email: “testemail2@emailcom”
                     firstName: “Test"
]

Upvotes: 0

Views: 200

Answers (2)

dseminara
dseminara

Reputation: 11935

If you want to remove elements from an array, I recommend you to use filter function

test = test.filter(function(val, idx) {
  if(true) { // a condition about val
    return false; // return false to EXCLUDE
  } else {
    return true; // return false to INCLUDE
  }
});

Upvotes: 1

Malk
Malk

Reputation: 11983

Just iterate through the array backwards. Then, removing elements from the array only affects the indices of elements that the loop has already dealt with:

for (var idx = test.length-1; idx>=0; idx--){
   if(true){
         test.splice(idx, 1);
   }
}

Upvotes: 1

Related Questions