Seek and Destroy - Question

Working on this challenge, can someone help me understand why this solution is not behaving as expected (filtering out the argument values after the 1st one)?

Here is the challenge: https://www.freecodecamp.org/challenges/seek-and-destroy

Here is my solution:


function destroyer(arr) {

  function include (val) {
    for (var i = 1; i < arguments.length; i++) {
      if (val !== arguments[i]) {
        return true;
    }
    }
  }
  
  var newArr = arr.filter(include);
 
  return newArr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);


Look at where you’re accessing arguments, it’s inside the include function.

1 Like

If the element is one of the arguments, I need to filter it out. Shouldn’t I be able to reference arguments within the callback function?

The arguments object in the destroyer function is different from the arguments object in include. You’re trying to access the destroyer arguments, but you’re actually accessing the include arguments. You’ll need to slice those destroyer arguments into a variable to be accessed in the include function.

1 Like

Makes sense, thanks guys!

Here is my modified version that passes the tests. I had a logic flaw in the original code in addition to the argument reference inside the function. Any feedback is welcome on my solution. Thanks for the help!


function destroyer(arr) {

  //create an array from the arguments
  var args = Array.prototype.slice.call(arguments);
  args = args.slice(1); //exclude the 1st argment
  
  //create callback function for filter that removes values that appear after the 1st argument
  function include (val) {
    if (args.includes(val)) {
        return false;
    } else {
      return true;
    }
  }
  
  //filter the array and assign to newArr
  var newArr = arr.filter(include);
  
  //return the filtered array
  return newArr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);


Looks good, but you can clean some things up.

You can reduce the argument slicing down to one line with this:

var args = Array.prototype.slice.call(arguments, 1);

Also, you should be wary whenever you see an if/else that returns a boolean. You can have the same functionality with this:

function include(val) {
  return !args.includes(val);
}
1 Like