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.
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];
> })
> }
This is not the reason, but what you’re doing does fix it and made it obvious why:
@joshfer2000arguments 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.
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()
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.