Seek and Destroy question

Seek and Destroy question
0.0 0

#1

Hi guys,

I’m trying to understand the intermediate solution to the problem.

function destroyer(arr) {
var args = Array.from(arguments);
var test = arr.filter(function(val){
return !args.includes(val);
});
return test;
}

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

In the variable “test”, I understand that arr refers to arr[0] by default, but how does “args” work inside the filter method?

Because from my understanding, arr[0] is basically [1, 2, 3, 1, 2, 3] – but args is the whole arguments array [[1, 2, 3, 1, 2, 3], 2, 3]. How is [1, 2, 3, 1, 2, 3] not cancelled out by filter?

I hope that makes sense. Thanks in advance!


#2

Because [1,2,3,1,2,3] is an array and arrays are hard to compare directly (open your console and type [1] == [1] and you’ll see it’s false).

Personally, I would manually exclude it from the filter, because I agree with you that it’s confusing.


#3

arr does not refer to arr[0] by default. arr does refer to arguments[0], because arr is the first argument passed into the function.

Since you only need the function arguments after arr, then why not slice them off args, so it does not include the first argument?


#4

Hey thanks for this! I guess slicing args would only leave it with the last 2 arrays, which is what we want to compare the first array to, which makes perfect sense.

But then… how come it still works without slicing??

it’s basically comparing args[0] with args[0], args[1], args[2], when it’s not sliced, right?


#5

On any given iteration of the filter function, it returns the the evaluation of !args.includes(val). This checks if args does NOT include val? If it does not include val, then put val in the new array called test.

Let’s walk through what the code inside the filter is evaluating during each iteration.

Iteration #1 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 1, so Does args include 1? It does not, so put it in test.

Iteration #2 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 2, so Does args include 2? It does, so do not put it in test

Iteration #3 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 3, so does args include 3? It does, so do not put it in test.

Iteration #4 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 1, so does args include 1? It does not, so put it in test.

Iteration #5 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 2, so Does args include 2? It does, so do not put it in test.

Iteration #6 - args = [ [ 1, 2, 3, 1, 2, 3 ], 2, 3 ] and val = 3, so Does args include 3? It does, so do not put it in test.