-
arr
is the actual array given as the first argument.
-
args
is the rest of the arguments given to destroyer
- so like destroyer([1,2,3,1,2,3], 1, 2)
, args
would be [1,2]
.
-
filter
goes through each value in an array one by one and tests them each in turn. val
in the callback is just a name for the current value being tested. It returns an array containing every value that tests as true.
-
includes
checks if the value given to it is in an array - [1,2].includes(2)
would be true, [1,2].includes(4)
would be false.
- the unary
!
negates. So ![1,2].includes(2)
would be false. You want the filter to return false if the target value is one of the values in args
- this will drop it from the return value.
If I add console logs to the function, I can see what happens when the function funs, then each iteration of filter as it goes through the array:
Version of the solution with console logging added:
function destroyer(arr) {
console.log(`The array to filter is [${arr.join(',')}]`);
var args = Array.from(arguments).slice(1);
console.log(`The values to destroy are [${args.join(',')}]`);
return arr.filter(function(val) {
const valIsATarget = (args.includes(val)) ? '*is*' : '*is not*';
const whatToDo = (args.includes(val)) ? '*filter it out*' : '*keep it*';
console.log(`
Iterating through array, current value being checked is ${val}.
The value ${valIsATarget} one of the values that should be destroyed.
Return *${!args.includes(val)}* for it, which will *${whatToDo}*.
`);
return !args.includes(val);
});
}
If I run the above in the console, I get:
> destroyer([1,2,3,1,2,3], 1, 2)
The array to filter is [1,2,3,1,2,3]
The values to destroy are [1,2]
Iterating through array, current value being checked is 1.
The value *is* one of the values that should be destroyed.
Return *false* for it, which will **filter it out**.
Iterating through array, current value being checked is 2.
The value *is* one of the values that should be destroyed.
Return *false* for it, which will **filter it out**.
Iterating through array, current value being checked is 3.
The value *is not* one of the values that should be destroyed.
Return *true* for it, which will **keep it**.
Iterating through array, current value being checked is 1.
The value *is* one of the values that should be destroyed.
Return *false* for it, which will **filter it out**.
Iterating through array, current value being checked is 2.
The value *is* one of the values that should be destroyed.
Return *false* for it, which will **filter it out**.
Iterating through array, current value being checked is 3.
The value *is not* one of the values that should be destroyed.
Return *true* for it, which will **keep it**.
Array [ 3, 3 ]
(first line is input into the console, the last line is the final return value)