Aki G
Aki G

Reputation: 39

how to use Array.filter instead of traditional looping-O(n^2)?

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.

--> I am trying to use array.filter(), new to it...instead of two loops...this is the code...

function destroyer(arr) {
 var args = Array.from(arguments);
 var array = args.slice(1);
 //console.log(array);
  
return array.forEach(function(val){
 return arr.filter(function(tar){
  return tar!==val;  
 });
});
   }

var ans = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(ans);
It doesn't get me the desired solution?! Any clues...

Upvotes: 0

Views: 54

Answers (3)

JLRishe
JLRishe

Reputation: 101738

You can use the following. This has a complexity of O(N * M), which I think is pretty much the best you're going to get for this.

function destroyer(arr) {
  var args = Array.from(arguments);
  var array = args.slice(1);
  
  return arr.filter(function(tar){
    return array.indexOf(tar) === -1;
  });
}

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

Upvotes: 0

Khauri
Khauri

Reputation: 3863

Your method works fine, you're just not properly returning the values.

A better way would be to use filter by itself as suggest by another answer, but if for some reason you wanted it to do it with forEach and filter here's how.

function destroyer(arr) {
 var args = Array.from(arguments);
 var array = args.slice(1);
 
  array.forEach(function(val){
   arr = arr.filter(function(tar){
      return tar!==val;  
   });
  });
  return arr;
}

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

Upvotes: 1

n4gys4nyi
n4gys4nyi

Reputation: 933

with .indexOf() function you can check if the element is in the array or not.

function destroyer(arr) {
    var args = Array.from(arguments)
    var array = args.slice(1)

    return arr.filter(function(v){
        return array.indexOf(v) === -1
    })
 }

var ans = destroyer([1, 2, 3, 1, 2, 3], 2, 3);

console.log(ans) will display [1, 1]

Upvotes: 1

Related Questions