Tap Tap - 2 years ago 130
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
, 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 Source

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
  return toRemove.indexOf( el ) < 0;
} );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download