Seek and Destroy- algorithms challenge - Help

I solved the challenge, but i do not htink i’m right, because the freeCodeCamp text editor shows me this warning message : ! Don’t make functions within a loop.
In this case i used filter within a loop and i can’t see another way to do this. Plz help :upside_down:
Am i right ? Or there is a smarter way to solve the problem ?

Link To The Challenge

My code :

function destroyer(arr) {
// Remove all the values
var array = arguments[0];
var args = arr.slice.call(arguments);
args.shift();
for(i= 0 ; i <args.length;i++){
array = array.filter(function(val){
return val!=args[i];
});
}
return array;
}

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

OK, I’ll give this a try…

I don’t think this is a fatal mistake, I think that it’s just warning you that you’re doing something “iffy”. That function (I think) is going to be created each time the loop iterates and then destroyed at the end of the iteration - Wow! That’s a lot of work. I think it would be more efficient to create the function outside of the loop and call it. That way it is only created and destroyed once. It may not matter much on this program, but imagine if you had a loop that iterated thousands or millions of times. This does the same thing:

function destroyer(arr) {
// Remove all the values
  var array = arguments[0];
  var args = arr.slice.call(arguments);
  
  args.shift();
  
  for(i= 0 ; i <args.length;i++){
   array = array.filter(myFunc);
  }
  
  return array;

  function myFunc(val) {
    return val!=args[i];
  }
}
1 Like

Thank you so much!!
i think its important to learn the best pratices since the beginning.