Help with Seek and Destroy

Help with Seek and Destroy
0

#1

I can not get the seek and destroy challenge to work. This is my latest attempt. Can anyone tell me why I am getting an error of “TypeError: 2 is not a function”?

function destroyer(arr) {
  // Remove all the values
  var filtered;
  for (var i = 1; i < arguments.length; i++ )
  {  
    for (var j = 0; j < arr.length; j++)
    {
         if (arguments[i] === arr[j])
           {
     
              filtered = arr.filter(arguments[i]);
           }
    }
  }
  //alert(filtered);
  return arr;
}

#2

Array.prototype.filter takes a function as an argument. You’ve given it an integer. Here’s what filter should look like:

var newArray = arr.filter(function(arrayItem) {
     return arrayItem === something
});

This will go through all of the items in the array arr and the items that are strictly equal to something in a new array called newArray.


#3

arr.filter() expects a function to be passed as an argument :

arr.filter( function(itemInArray){ } )

the arguments[i] you passed is not a function but a number, if I remember well.

This is how filter() works :

// we want to remove number 2
var filtered = [1,2,3].filter(function filtering(item){
    return item !== 2;
    // (item !== 2) evaluates to true or false
    // it is the same as doing : 
    /*
    if(item !==2) {
      return true;
    } else {
      return false;
    }
    */  
});

console.log(filtered); // [1,3]

The “filtering” function is invoked for each element in the array.The “item” parameter represents each element of the array.The “filtering” function must return true or false.If it returns true, the item is kept in the array, otherwise it is removed from the array.

I choose to name the function “filtering”, but it could have no name of course.You can replace “item” with another name as well.


#4

Is there a better way to accomplish this challenge without using .filter()?


#5

Ok, tried a different approach. Any idea as to why this is removing a 1 and the 3’s and leaving all the 2’s?

```  // Remove all the values
```  var newArr = arr;
```  for (var j = 0; j < arr.length; j++)
```  {
```    for (var i = 1; i < arguments.length; i++)
```    {
```      if(arr[j] === arguments[i])
```        {
```          arr.splice(arr[j], 1);
```        //alert(arguments[i]);
```        }
```    }
```  }
``` return arr;

#6

the first argument you passed to splice is not the index of the element you want to remove, but arr[j], which is the value of the element.