Remove all elements contained in another array
Use the Array.filter()
method:
myArray = myArray.filter( function( el ) { return toRemove.indexOf( el ) < 0;} );
Small improvement, as browser support for Array.includes()
has increased:
myArray = myArray.filter( function( el ) { return !toRemove.includes( el );} );
Next adaptation using arrow functions:
myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );
The filter
method should do the trick:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];const toRemove = ['b', 'c', 'g'];// ES5 syntaxconst filteredArray = myArray.filter(function(x) { return toRemove.indexOf(x) < 0;});
If your toRemove
array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1)
rather than O(n)
.
const toRemoveMap = toRemove.reduce( function(memo, item) { memo[item] = memo[item] || true; return memo; }, {} // initialize an empty object);const filteredArray = myArray.filter(function (x) { return toRemoveMap[x];});// or, if you want to use ES6-style arrow syntax:const toRemoveMap = toRemove.reduce((memo, item) => ({ ...memo, [item]: true}), {});const filteredArray = myArray.filter(x => toRemoveMap[x]);
ECMAScript 6 sets can permit faster computing of the elements of one array that aren't in the other:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];const toRemove = new Set(['b', 'c', 'g']);const difference = myArray.filter( x => !toRemove.has(x) );console.log(difference); // ["a", "d", "e", "f"]
Since the lookup complexity for the V8 engine browsers use these days is O(1), the time complexity of the whole algorithm is O(n).