Skip to main content
2 of 3
edited title
janos
  • 113.1k
  • 15
  • 154
  • 396

Filter array elements using variable number of filters

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.

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. var filterItems = []; for (i = 1 ; i < arguments.length; i++ ){ filterItems.push( arguments[i]); } // 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?

beauk
  • 23
  • 4