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
  • 533
  • 1
  • 6
  • 18

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
  • 32,209
  • 6
  • 49
  • 63
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
  • 15,230
  • 5
  • 28
  • 32
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
  • 323,592
  • 20
  • 270
  • 324
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
  • 28,583
  • 5
  • 34
  • 61
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