Can somebody explain why my code doesn't work?

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function destroyer(arr, ...remove) {
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < remove.length; j++) {
    if (arr[i] === remove[j]) {
      arr.splice(i, 1);
    }
  }
}
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/93.0.4577.82 Safari/537.36

Challenge: Seek and Destroy

Link to the challenge:

You should not use splice on an array that you’re attempting to loop over because splice changes mutates it in place. Basically on an iteration where you remove a value at [i], the following value that was once at [i + 1] is now at [i]. But the loop has already ended that iteration, so it will skip that value.

My hint for you is, instead of removing items from the array given to you, instead try to build a new array up from nothing that only includes the correct values.

Thank you for the recommendation. I improved the code a bit not to mutate the original array.

function destroyer(arr, ...remove) {
  let newArr = [];
  for (i = 0; i < arr.length; i++) {
    if (!remove.includes(arr[i])) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

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

But still, it gives an error. I figured that it doesn’t give error in VS Code, it gives only if I use strict mode.

The error says:

ReferenceError: assignment to undeclared variable i

Where do you think the problem is?

(this is a rhetorical question but I’d like you to debug it)

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