0

So I have this code, which does what it needs to do, which is return an input array minus any values that match the arguments after the array. But, I am having trouble figuring out how to iterate through all the arguments. Here is what I have working -

function destroyer(arr) {
  var arg2 = arguments[1];
  var arg3 = arguments[2];
  var arg4 = arguments[3];
  var result = arr.filter(function(arg) {
    if (arg != arg2 && arg != arg3 && arg != arg4) {
      return (arg);
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

And here is my attempt at iterating through all arguments with a for loop. It is not working and I am struggling to conceptualize what exactly I am pumping through my callback in the arr.filter here -

function destroyer(arr) {
  var result = arr.filter(function(arg) {
    for (var i = 1; i < arguments.length; i++) {
      if (arg != arguments[i]) {
        return (arg);
      }
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Is this close to where I need to be or am I way off here?

1 Answer 1

1

The arguments variable is set on each function call, including the call to your .filter() callback. Thus arguments in that callback is not what you think it is.

You can do what you're trying to do with .indexOf, and you'll need to copy they arguments into another array:

function destroyer(arr) {
  var badValues = [];
  for (var i = 1; i < arguments.length; ++i)
    badValues = arguments[i];
  return arr.filter(function(value) {
    return badValues.indexOf(value) < 0;
  });
}

It's popular to use .slice() to copy all or part of the arguments object:

  var badValues = [].slice.call(arguments, 1);

You can do that if you like the brevity, but passing the arguments object out of a function makes it very hard to optimize.

2
  • Thanks I got a version of this to work. Notable changes were pushing the arguments to badValues and setting the filter function to test for indexes === -1.
    – slurrr
    Sep 24, 2015 at 3:55
  • 1
    @slurrr yes sorry I got the test backwards :) Glad you worked it out!
    – Pointy
    Sep 24, 2015 at 5:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.