Splice messes up my loop

So I wrote:

function bouncer(arr) {
  for (var i=0; i<arr.length; i++){
    if (!!arr[i]){
    } else {
      arr.splice(i, 1); 
    }
  }
  return arr;
}

bouncer([7, "ate", "", false, 9]);

I couldn’t figure out why it was only removing "" and not false but now I see that when it removes "" at index 2 false is immediately placed into index 2 but the for loop increments to 3 bypassing the false value. How do I account for this?

You don’t. You should not mutate an array as you iterate over it. You should instead make a new array.

The most obvious way as for me is to decrement counter in your else block.

It is not recommended. Avoid modifying your array as you iterate over it unless there is no other way to solve your problem.

Yes, I know it’s a bad practice, just the first idea came up to my mind when I saw the code.
In fact, pushing “non-false” values into another array is shorter and more easy to read, because it does not even require else block.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.