Neong Neong - 2 months ago 8
Javascript Question

JavaScript Remove Multiple Values from Array Using Filter and Loop

I'm new here and need some help with writing a function

destroyer()
to remove multiple values from an array.

The destroyer() function passes in an array and additional numbers as arguments. The idea is to remove the numbers from the array.

E.g.

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


Output:
[1, 1]


destroyer(["tree", "hamburger", 53], "tree", 53)


Output:
["hamburger"]


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


Output:
[]


Note: the examples only show 2 additional numbers to remove. But the function destroyer() should be able to remove any number of values (i.e. 4, 5, or 6 parameters).

However, my code does not produce the same result. Specifically, using console.log, I see that my filterer function does not loop properly.

1) Can anyone help me debug?

2) Any better way to write this function?

Thank you very much!!!

function destroyer() {

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

var itemToRemove = args.slice(1);
console.log(itemToRemove);
var newArr = args[0];
console.log(newArr);

function filterer(value) {

for (var i = 0; i < itemToRemove.length; i++) {
console.log(i);
console.log(itemToRemove[i]);
if (value != itemToRemove[i]) {
return value;
}
}
}

return newArr.filter(filterer);
}

Answer

Your filterer function can be much simpler:

function filterer (value) {
    return itemToRemove.indexOf(value) === -1;
}