Seek and Destroy (need help)

I am trying to loop through all the arguments in my function (except the first) and filter out the numbers that i am looping in the array (which would be the first argument). I am not sure why this is not working. Thanks.


function destroyer(arr) {
  // Remove all the values
  for(let i = 1; i < arguments.length; i++){
      arr = arr.filter(function(x){
      return x !== arguments[i];
    })
  }
  return arr;
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

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

Link to the challenge:

what makes you think this is not working?

the entire array that is in the argument was printed, instead of the modified array.

Emm, I’m not actually sure why this doesn’t work, but it seems to be to do with scoping and the loop because:

Edit: I’m an idiot, see my other reply

function destroyer(arr) {
  for(let i = 1; i < arguments.length; i++){
    arr = arr.filter((x) => x !== arguments[i])
  }
  return arr;
}

Works absolutely fine.

As does doing the operations manually (not that you would do that, just for comparison):

> arr = [1, 2, 3, 1, 2, 3];
Array(6) [ 1, 2, 3, 1, 2, 3 ]
> arr = arr.filter(function (x) { return x !== 2; })
Array(4) [ 1, 3, 1, 3 ]
> arr = arr.filter(function (x) { return x !== 3; })
Array(2) [ 1, 1 ]

don’t use arguments inside loop it is an array like object but not true array, therefore, filter function was evaluating everything true.
just modified your code:

> function destroyer(arr) {
>   // Remove all the values
>   let args = [...arguments]
>   for(let i = 1; i < arguments.length; i++){
>       arr = arr.filter(function(x){
>       return x !== args[i];
>     })
>   }

return arr;
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

This is not the reason, but what you’re doing does fix it and made it obvious why:

@joshfer2000 arguments refers to the arguments of a function. So if you use it like

arr.filter(function(x) { return x !== arguments[i]; })

arguments is the arguments for that function above that you’re giving to filter.

If you use an arrow function, arrow functions do not have an arguments object; arguments points at the arguments of the outer function, so it works fine. Or you copy the arguments from the outer function and use those, as @avatarfreak did.

please refert to The arguments object - JavaScript | MDN
and know the actual reason… `

Note: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn’t have Array 's built-in methods like forEach() and map()

please refer to the links given above

`

That’s irrelevant, it’s because arguments refers to the arguments for the currently scoped function, @joshfer2000’s solution is failing because of that. I’m sorry, but what you’ve posted literally contradicts what you’re saying.

1 Like