Need to help to understand challenge "Seek and Destroy" in JS

Hi everybody!
I have difficulty while studying “solution 1” of challenge “Seek and Destroy” in JS lesson. I will copy again “Solution 1” code to here :

function destroyer(arr) {
  let valsToRemove = Object.values(arguments).slice(1);

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < valsToRemove.length; j++) {
      if (arr[i] === valsToRemove[j]) {
        delete arr[i];
      }
    }
  }
  return arr.filter(item => item !== null);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Follow my understand: let valsToRemove = Object.values(arguments).slice(1); will create an array: [2, 3] and due to slide() will not mutate the original arr so arr also keep: ([1, 2, 3, 1, 2, 3], 2, 3).
But follow the code arr in loop (arr.length, arr[i]) is only first element: [1, 2, 3, 1, 2, 3]
I hope get your explanation for my understanding!
Thanks so much!

What you are misunderstanding is that, arr is only the array [1, 2, 3, 1, 2, 3].
Which means, first parameter is the value which is passed in first.
What I mean is, arr will be the first argument which comes before the first , .
In this case that the first argument is an array [1, 2, 3, 1, 2, 3] so arr is it.
But if I call the function like destroyer([[1, 2, 3], [1, 2, 3]], [1, 2, 3]); , arr will be [[1, 2, 3], [1, 2, 3]].

Here for more: Can someone explain a line of code in intermediate-algorithm-scripting 3rd challenge("Seek and destroy") - #5 by AndrewAung11

1 Like

That’s great! This matter took a lot of my time for thinking but can not until reading your explanation and your link. Thanks you very much!

1 Like

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