Help with Falsy Bouncer

Why doesnt this code/solution work for falsy bouncer challenge:

function bouncer(arr) {

  arr.forEach((e)=> {

      if (!e){

      arr.splice((arr.indexOf(e)),1);

      } 

  })

  return arr;

}

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

You are altering the array you are looping. It goes through on the third pass and check the empty string. It removes that empty string and everything gets bumped up one. Then it does the fourth pass. But false used to be the fourth element but is not the third so it got skipped over. I think your code would not work if there are every consecutive falsy values.

It might work if you went backwards through the array.

yes , it only removes one element succesfully.

My takeaway from this has been:
do not mutate the array inside forEach.

That’s a good take away. Mutating inputs as you iterate on them gets tricky.

2 Likes

would there be a nuanced way to achieve the goal here.
meaning, is there a function in javascript that returns a copy of changed array, while not mutating the original array

This might help:

1 Like