0

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"
]
3
  • 2
    How about using .filter instead? Unless you really have to mutate the array. Commented Sep 15, 2014 at 19:53
  • 2
    for (var i=test.length-1;i>=0;i--){} Commented Sep 15, 2014 at 19:54
  • Isn't it completely obvious that you're both iterating and modifying the array at the same time ? Doesn't this ring a bell ? Commented Sep 15, 2014 at 20:04

2 Answers 2

1

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
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Filtering and reassigning is not exactly the same thing. Why do you recommend this method? Here is a perf (jsperf.com/array-mutations) it doesn't seem to help performance, especially as the array grows very large.
1

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);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.