4

So I have one array:

var array1 = ['one', 'two', 'three', 'four', 'five']

And another:

var array2 = ['two, 'four']

How can I remove all the strings from array2 out of array1?

scottt
  • 7,008
  • 27
  • 37
j_d
  • 2,818
  • 9
  • 50
  • 91
  • 1
    Possible duplicate of [What is the fastest or most elegant way to compute a set difference using Javascript arrays?](http://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-way-to-compute-a-set-difference-using-javasc) –  Apr 07 '16 at 08:33

4 Answers4

4

Just use Array#filter() and Array#indexOf() with bitwise not ~ operator for checking.

~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

var array1 = ['one', 'two', 'three', 'four', 'five'],
    array2 = ['two', 'four'];

array1 = array1.filter(function (a) {
    return !~array2.indexOf(a);
});

document.write("<pre>" + JSON.stringify(array1, 0, 4) + "</pre>");
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Try this.

array2.forEach(item => array1.splice(array1.indexOf(item),1));
Lewis
  • 14,132
  • 12
  • 66
  • 87
0

in jquery with inArray method:

for(array1)
  var idx = $.inArray(array1[i], array2);
  if (idx != -1) {//-1 not exists 
     array2.splice(idx, 1);
  } 

}

ZaoTaoBao
  • 2,567
  • 2
  • 20
  • 28
0

var array1 = ['one', 'two', 'three', 'four', 'five']
var array2 = ['two', 'four']
    
array1 = array1.filter(function(item){
   return array2.indexOf(item) === -1
})
// ['one', 'three', 'four', 'five']

document.write(array1)
xcodebuild
  • 1,121
  • 9
  • 17