Seek and Destroy challenge

Seek and Destroy challenge
0

#1

Hi, i’m doing the ‘Seek and Destroy’ JavaScript Challenge:

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.

and here is my code.

function destroyer(arr) {

var newArr = [];

for (var i=0;i<arguments[0].length;i++){
if (arguments[0][i] == arguments[1] || arguments[0][i] == arguments[2]){

  arguments[0].splice(i,1);
  
}

else {
  newArr.push(arguments[0][i]);
}

}
return newArr;

}

The problem that I ran into is that it doesn’t work for string type input such as:

destroyer([“tree”, “hamburger”, 53], “tree”, 53) should return [“hamburger”].

Can anyone help me to solve the problem? Also, the challenge suggests to use ‘array.filter()’.

Thx


#2

Hey @teguhsam,
like you mentioned, this exercise is suggested to be used with filter. Your code obviously does not do that.
The filter functions iterates over the array and invokes a function, given as a parameter, on each array element.
What you need to do is filter out any element that may be contained already in the original array.

You can go here to read more about Array.filter:

https://www.w3schools.com/jsref/jsref_filter.asp


#3

The problem with splice is that it mutates the array, this is not good because you are mutating the array that the condition of the for loop is based on. Therefore, if you want to use splice while keeping the original array intact , you have to perform a deep copy on the original array and then work on that.