How To Remove All Elements Contained in Another Array in JavaScript – Definitive Guide

This tutorial teaches you how to remove all elements contained in another array in JavaScript and when to use each method.

Answer: use the array.filter(), and the includes() method.

Remove All Elements Contained in Another Array Using Filter And Includes (Simple Method)

The filter() method creates a shallow copy of a portion of an array by filtering the element that passes a specific condition.

  • Use the includes() method to specify the condition that the element must exist in another array.
  • In this way, you can remove the elements present in another array.

Use this method when you are working with numeric arrays, and the numeric array might contain NaN in it. The NaN property represents a value, Not a Number.

Code

The following code uses the includes() method to check if the second array doesn’t contain an element and adds the element to the newly created array.

var numArray = [1, 2, 3, 4, 5, NaN]

var toRemove = [4, 5, NaN];

removedArray = numArray.filter(function(el) {
  return !toRemove.includes(el);
});

console.log(removedArray);

Output

[1, 2, 3]

Remove All Elements Contained in Another Array Using Filter() and IndexOf()

This section uses the filter() method and indexOf() method to remove all elements in another array.

The indexOf() method checks if the array element is present in the array:

  • Returns the element index if it is present
  • Returns -1 if the element is not present

The indexOf() element returns -1 in the case of the NaN property. Hence, the NaN items will not be removed when using the indexOf() method.

Use this method when you’re working with string/character arrays or numeric arrays that don’t contain the NaN property.

Code

The following code demonstrates how to use the indexOf() method to remove the elements.

var numArray = [1, 2, 3, 4, 5, NaN ]

var toRemove = [4, 5, NaN];

removedArray = numArray.filter(function(el) {
  return toRemove.indexOf(el) < 0;
});

console.log(removedArray);

Output

The NaN value was not removed though it was available in another array because the indexOf() method did not find it.

[1, 2, 3, NaN]

Remove All Elements Contained in Another Array Using Filter() with Arrow function

This section teaches you how to use the arrow function with the filter() method.

The arrow function provides better readability of the code and can be used with the methods associated with the array, such as map(), filter() and so on.

Apart from shorter code and better readability, there is no significance in using the arrow function over the normal function. Hence, it is purely the developer’s preference.

Code

var numArray = [1, 2, 3, 4, 5, NaN]

var toRemove = [4, 5, NaN];

removedArray = numArray.filter((el) => !toRemove.includes(el));

console.log(removedArray);

Output

[1, 2, 3]

Additional Resources

Leave a Comment