Seek and Destroy - Question

Seek and Destroy - Question
0

#1

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);



#2

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


#3

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?


#4

Each function has it’s own argument’s object. When you reference arguments.length and arguments[i] while inside the include function, you are referencing the arguments passed into the include function which in this case are the filter callback function arguments. If you want to refer to the arguments passed into the destroyer function, I recommend you slice them out into an array and reference that array.


#5

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.


#6

Makes sense, thanks guys!


#7

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);



#8

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);
}