Tap Tap - 6 months ago 27
Javascript Question

Javascript arrays: remove all elements contained in another array

I am looking for an efficient way to remove all elements from a javascript array if they are present in another array.

// If I have this array:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// and this one:
var toRemove = ['b', 'c', 'g'];


I want to operate on myArray to leave it in this state:
['a', 'd', 'e', 'f']


With jQuery, I'm using
grep()
and
inArray()
, which works well:

myArray = $.grep(myArray, function(value) {
return $.inArray(value, toRemove) < 0;
});


Is there a pure javascript way to do this without looping and splicing?

Answer

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
  return toRemove.indexOf( el ) < 0;
} );
Comments