I'm taking online JavaScript courses and I'm curious about one of the tasks:
We'r provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. We have to remove all elements from the initial array that are of the same value as these arguments.
Here's my solution, but it doesn't works:
function destroyer(arr) {
// Separating the array from the numbers, that are for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// This is just to check if we got the right numbers
console.log(filterArr);
// Setting the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
}
}
// Let's check what has been done
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I was able to find a solution, however it doesn't makes any sense to me, that's why I'm posting this question; can you please tell me why the following code works:
function destroyer(arr) {
// Separating the array from the numbers, that are for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// This is just to check if we got the right numbers
console.log(filterArr);
// Setting the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
// This true boolean is what makes the code to run and I can't // understand why. I'll highly appreciate your explanations.
}
return true;
}
// Let's check what has been done
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Thank you for the heads up!
filterneeds to return some value. If it’s truthy (e.g.true), the element is kept, if it’s falsy (e.g.false), it’s removed. You’re only returningfalseorundefined(automatically) which is falsy.filtermethod must returntrueif you want to retain the element. If it only returnsfalseit will remove everything. Not returning a value is treated as if returningfalse.