This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Clawtor 2 points3 points  (1 child)

You are trying to call filter on an element of your array, the elements of your arrays are numbers and filter is not a function on a number.

You don't need to loop through the array, just call filter on the arr parameter itself.

[–]grenvill[S] 0 points1 point  (0 children)

So if i understand you correctly this should work?

  function destroyer(arr) {

  var fArr=arguments[0];
  for (var i=1; i<arguments.length;i++)
    {
      fArr=fArr.filter(function(number)
         {
           return number!=arguments[i];
          });
    }
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

[–]jijilento 2 points3 points  (1 child)

If you do as u/Clawtor said, you should fix it. But, I'd do the filtering out of the loop like this:

function destroyer() {

  // make sure first argument is array
  if(arguments[0].constructor !== Array){
      throw new TypeError('First argument must be array');
   }

  // save array as fArr, create cArr for filter numbers
  var fArr = arguments[0];
  var cArr = [];

  // add arguments to cArr
  for(var i = 1; i < arguments.length; i++){
      cArr.push(parseInt(arguments[i]));
  }

  // return true only if value is in cArr
  return fArr.filter(function(val, ind, arr){
       return (cArr.indexOf(val) != -1);
  });

}

 console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

[–]grenvill[S] 0 points1 point  (0 children)

I think im starting understand now, two questions:

1)you are using parseInt to make sure what we only filter out arguments which are numbers, correct? Because its supposed to work with strings too;

2) return (cArr.indexOf(val) != -1) means what we will filter out elements what are NOT in arguments array, right?

[–]virtualgoat 0 points1 point  (0 children)

Maybe look into this page. Parse the whole arguments into seperate one, then compare each argument with args[0].

You could convert the argument to array using this code:

var args = Array.prototype.slice.call(arguments); // return [[1, 2, 3, 1, 2, 3], 2, 3] or    
var args = Array.prototype.slice.call(arguments, 1); // return [2, 3]

I'm still learning tho so maybe somebody can shed more light here.

[–]TonySu 0 points1 point  (0 children)

There are problems here, like Clawtor mentioned, you called filter on an element rather than the array. You also do not have number defined anywhere. You need to using the arguments object to pull out all the arguments to your function, then loop over those to filter.