Oli Oli - 5 months ago 13
Javascript Question

Javascript: please help me understand this function

I've been trying to understand this function for quite a while, but it just doesn't make sense to me. The goal of the function is to remove any numbers within the array of arguments that match the other argument numbers.

Why is it necessary to slice the array for the function to work?

Is args.splice(0,1) redundant? I removed it and nothing changed.

It seems like the filter function does the bulk of the work, but I don't see how it actually filters for the numbers...

function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
args.splice(0, 1);
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Answer

Let's go through it line by line:

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

JavaScript's arguments variable is similar to an array but it's not an array. You can try this yourself: arguments instanceof Array will give false. So applying the slice method from the Array prototype will simply convert arguments to a real array.

args.splice(0, 1);

This is to remove the first argument, which is arr in your case.

return arr.filter(function(element) {
  return args.indexOf(element) === -1;
});

This will go through all the numbers in arr and will check each one of them if it exists in the arguments. When indexOf() returns -1 it means the element was not found in the array.