0

I have an array:

    var arr = [1,2,4,5,1,2,3,4,5];

And I have another array:

    var removeArr = [1,3,5];

I want it to remove elements in arr that has in the removeArr:

    var result = arr.filter(function(item){
                 return item != removeArr[???];
                 });

I have tried to iterate it using loop but it doesn't work.

GTHell
  • 603
  • 1
  • 8
  • 20

5 Answers5

2

You can reach the desired output using Array#filter aswell as Array#indexOf functions.

var arr = [1,2,4,5,1,2,3,4,5],
    removeArr = [1,3,5],
    result = arr.filter(function(item){
      return removeArr.indexOf(item) == -1;
    });
    
    console.log(result);
kind user
  • 40,029
  • 7
  • 67
  • 77
2

 var arr = [1,2,4,5,1,2,3,4,5];
 
 var removeArr = [1,3,5];
 
 var result = arr.filter(x => !removeArr.includes(x));
 
 console.log(result);
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
2

You could use a Set and test against while filtering.

var array = [1, 2, 4, 5, 1, 2, 3, 4, 5],
    removeArray = [1, 3, 5],
    result = array.filter((s => a => !s.has(a))(new Set(removeArray)));
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
var result = arr.filter(function(item){
    return removeArr.indexOf(item) === -1; // if the item is not included in removeArr, then return true (include it in the result array)
});
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

You can check if a value is in an array by checking if the index of the item is not -1.

var result = arr.filter(item => removeArr.indexOf(item) === -1)

claireinez
  • 39
  • 4