This is a question generated from a coding challenge, and I solved it, but I'm just not sure it's a great solution, nor am I sure why the first way I was trying didn't work.
Challenge: Implement a function called destroyer()
. "You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments."
Some test cases: - destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1] - destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"]
So here is the function that passed the test.
function destroyer(arr) {
// make a temp array to store iterations of the loop used to filter
var newArr = [];
// get the items to filter from the arguments passed.
// EDIT: changed this for loop to use slice
var filterItems = Array.from(arguments).slice(1);
// use the array of items to filter, to filter the 'arr'
// NOTE:I get a warning about calling a function in a loop. but it works in my lab environment anyhow.
for (i=0; i < filterItems.length; i++){
newArr = arr.filter(function(el){ // cannot assign directly to arr here for some reason???
return el !== filterItems[i] }
);
arr = newArr;
}
return newArr;
}
Okay, so calling the function with this, the array passed in argument 1 gets filtered, removing any numbers passed later.
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
What didn't work, is using arr = arr.filter...
to iterate over the array passed into the function. Instead, I first had to output the filter into the temp newArray
and then reassign it in the for loop. That kind of confuses me. if I can change arr with arr = newArr
. Why does that work and not the other way where I output the arr.filter right back into arr?