Seek and Destroy one correct, one is wrong

Hi!

I have a code, but it was not working, then I decided to turn it into an arrow function, and then it worked, but I don’t know why! I mean, the code is EXACTLY the same, but it works with arrow function and not the other way. I have already checked the typo MANY times, and there is none. But there should be something I am missing out.

This is the non-working code:

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

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

This is the working code:

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

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

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy

That is because arrow functions do not have an arguments object, so arguments is the arguments object of the destroyer function.

In the code which does not use arrow function syntax, arguments of the callback function are the actual arguments of the callback function and not the destroyer function’s arguments.

You do not even need the for loop. Just use the filter but first create another an array (think slice) of just the arguments after the first argument and use indexOf or includes to check for the existence of the sliced array’s values in newArr.

1 Like