Currently, I am enrolled in online JavaScript courses and I'm intrigued by a particular task:
In this task, we are given an initial array (the first argument in the destroyer function) followed by one or more arguments. The goal is to eliminate all elements from the initial array that share the same value as these arguments.
Below is my initial solution to the task, but unfortunately, it is not working as expected:
function destroyer(arr) {
// Separating the array from the numbers meant for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// Console log to verify the correct numbers
console.log(filterArr);
// Defining the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
}
}
// Check the progress made
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
While I did manage to find a solution, it doesn't quite make sense to me. Hence, I'm seeking clarification on why the following code actually works:
function destroyer(arr) {
// Separating the array from the numbers meant for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// Console log to verify the correct numbers
console.log(filterArr);
// Defining the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
// The 'true' boolean here is key to the code execution, and I'm struggling to grasp the reason behind it. I would greatly appreciate any insights you can provide.
}
return true;
}
// Check the progress made
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Thank you for any guidance and explanations!