Seek and Destroy - looking for explanation

Seek and Destroy - looking for explanation
0

#1

Tell us what’s happening:

Hey folks, I’ve been messing with what I thought would be a solution for a couple hours now and getting to the point of pulling my hair out. Can anyone tell me why this wouldn’t work?

Your code so far

function destroyer(arr) {
  // Remove all the values
  var args = Array.prototype.slice.call(arguments);
  
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < args.length; j++) {
      if (arr[i] === args[j] && i !== -1) {
        arr.splice(arr[i], 1);
      }
    }
  }
  
  return arr;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36.

Link to the challenge:


#2

You have a couple of issues. Answer these question and I will give you a few hints.

#1) Why are you starting j at 0? args[0] is [1, 2, 3, 1, 2, 3].

#2) What exactly to do you think arr.splice(arr[i], 1); does?


#3
  1. Yeah - I thought about that and even changed j to start at 1 to just skip the array but got the same result.

  2. When you asked that question I went back and thought about it some more - initially I thought the way I had it written would remove the item at the array index, but I switched it to just arr.splice(i, 1) and have three passing tests now. The way I have it written, splice should remove one item from the specified index (at least I think).

Edit: does splice not handle changes in array indexes well?

Edit 2: No, no it does not.

Edit 3: Finally got it working, iterated backwards in the for-loop rather than forwards.


#4

No it does not. If you would have written your original solution with:

arr.splice(i--, 1); 

i would have been decremented to account for the missing item.