JavaScript: Remove elements that occur in one array from another

Updated: March 13, 2023 By: Khue Post a comment

This concise, code-centric article will show you a couple of different approaches to removing all elements that occur in one array from another array in JavaScript. Before getting started, let’s see some real-world use cases for doing this:

  • Filtering search results: Suppose you have an array of search results, and you want to remove all the items that match a blacklist of terms. In this case, you could use the techniques in this article to filter out unwanted results and show only the relevant ones.
  • Merging data: If you have two arrays of data, you might want to combine them into a single array but exclude any items that appear in both arrays. This technique could be useful in merging data from two different sources while avoiding duplicates.
  • Parsing text: If you are working with text data, you might need to extract specific keywords or phrases while ignoring others. This technique can be helpful in removing irrelevant keywords from a list of extracted terms.
  • Cleaning data: Sometimes, data can contain duplicates or irrelevant values. In such cases, you could use the technique to remove all the unwanted values and clean up your data.

Now, it’s time to explore the solutions and write code.

Using the filter() and the indexOf() methods

One way to accomplish the task is to use the filter() method to iterate over the first array and return only the elements that are not in the second array.

Example:

// Define two arrays
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];

// Filter out the elements that are in toRemove
const filteredArray = myArray.filter(function (x) {
  return toRemove.indexOf(x) < 0;
});

// Print the result
console.log(filteredArray);

Output:

[ 'a', 'd', 'e', 'f' ]

The indexOf() method with a negative return means that the specified value was not found in the array or string.

Using the reduce() and the includes() methods

In terms of performance, this solution performs just as well as the previous one, even for large arrays.

Example:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 4];

// Filter arr1 to remove all elements that are in arr2
const filteredArr = arr1.reduce((acc, curr) => {
  if (!arr2.includes(curr)) {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(filteredArr);

Output:

[ 1, 3, 5 ]

Using loops

This approach works but it’s important to note that it is less efficient than preceding approaches, particularly for larger arrays, because it requires nested loops, which can slow down the execution time.

Example:

const arr1 = ['sling', 'academy', 'hello', 'world', 'javascript'];
const arr2 = ['hello', 'world', 'javascript'];
const result = [];

for (let i = 0; i < arr1.length; i++) {
  let found = false;
  for (let j = 0; j < arr2.length; j++) {
    if (arr1[i] === arr2[j]) {
      found = true;
      break;
    }
  }
  if (!found) {
    result.push(arr1[i]);
  }
}

console.log(result);

Output:

[ 'sling', 'academy' ]

This method is useful in helping you deepen your understanding of JavaScript, but in real applications, you should consider using either of the first two methods in this article.