Seek and Destroy splice not working fully

Tell us what’s happening:
Hi, I can’t figure out why the splice method is not working fully correctly, I have passed and failed some test.
These are the outputs from the console . I even replace the splice method to turn the position I want to destroy to 0 and it works. Please help

(2) [1, 1]
(3) [1, 5, 1]
(2) [1, 2]
VM4611:24 [2]
VM4611:24 [“hamburger”]
VM4611:24 (4) [12, 92, 65, “yacht”]

Your code so far


function destroyer(arr) {
  // Remove all the values
  var args = [...arguments].slice(1);

  for(let i = 0; i < arr.length; i++){
    for(let j = 0; j < args.length; j++){
      if(arr[i] == args[j]){
          arr.splice(i,1);
      }
    }
  }
  console.log(arr);
  return arr;




}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy

Because after you splice you are changing the index of your array.

Say:
arr = [0, 1, 2]
args = [0, 1]
i = 0

Then in the first iteration:
arr[0] = args[0] = 0
so, it wil splice and now you have
arr = [1, 2]
args = [0, 1]
i = 1

arr[1] = 2 != args[1] = 1;

So it won’t splice the new element at index 0, but it should.

You can either go back one step, decrementing i after each splice, or I am sure you can find a more elegant solution. =)

Cheers and happy coding.

ah i see thanks !, Your explanation is clear :smiley: . i’m going to look for better ways to solve this :slight_smile: