Seek & Destroy, what's going on here?

Can someone help me understand what is going on with my code? I can’t get it to pass all the tests… Not sure what is going on though, because the ones it is failing have multiple of the same element that need to be destroyed; it seems like the 2nd element remains. Yet in other examples from the testing, it removes all of them. I’m confused and any help/explanation would be appreciated!

function destroyer(arr) {

let i = 0,
    x = 0;

while (i < arguments.length){
    for(x in arr) {
      if(arr[x] == arguments[i]) {

  return arr;

destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3);

It only fails these tests:
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1] .
destroyer([2, 3, 2, 3], 2, 3) should return [] .

The rest pass.

Your bug stems from the fact that you are modifying your arr array as you are looping through it (i.e. splice). When you splice, the array gets shorter and the number of times it gets called is shortened. When you have an element at the end that needs to be removed, it gets skipped.


Thanks for the quick response! I’ll rethink how to solve this algorithm

1 Like

You’re definitely on the right track! Modifying arrays while you go through them are a common place for some quite nasty bugs.

Since this is intermediate scripting, I believe the curriculum should have covered the filter method on arrays. Maybe look into that.

And if you’re feeling up for it, instead of looping through arguments you could see if you can extract the things you need neatly with array destructuring and the rest operator.