0

I have the following piece of code:

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

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

It removes the elements from an array which equal the optional arguments. This code gives [1,1] as I expect.

But if I change the 4th line to

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

I get [1,2,3,1,2,3] instead, when I expect [1,1]. Why is that the case?

2
  • 3
    In the second case you use the arguments object of the inner function and not the outer one. Commented Sep 9, 2017 at 8:16
  • you could use arrow notation arr = arr.filter(x => x != arguments[i]); Commented Sep 9, 2017 at 8:20

1 Answer 1

2

Because when you use arguments within the anonymous function, you're accessing arguments of that function, not destroyer().

You will need to copy the arguments of destroyer(), preferably before your loop as follows:

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

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

Alternatively, an arrow function can also be used to achieve the same functionality:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

of course, if you're going to use ES6 ... function destroyer(arr, ...args) { return arr.filter(x => !args.includes(x)); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.