remove all elements of one array from another javascript

Removing Elements of One Array from Another in JavaScript

Have you ever needed to remove all elements of one array from another array in JavaScript? This can be a common task when dealing with arrays that have overlapping values or when trying to filter out unwanted elements. Here are a few ways to accomplish this task:

Method 1: Using filter() and includes()

One way to remove elements from an array is to use the filter() method along with the includes() method. Here's an example:


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

const filteredArr = arr1.filter(num => !arr2.includes(num));

console.log(filteredArr); // Output: [1, 3, 5]

In this example, we have two arrays: arr1 and arr2. We want to remove all elements of arr2 from arr1, so we use the filter() method to loop through each element of arr1 and return only the elements that are not included in arr2. The includes() method is used to check whether each element of arr1 is included in arr2. The resulting array is stored in the filteredArr variable.

Method 2: Using splice()

Another way to remove elements from an array is to use the splice() method. Here's an example:


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

arr2.forEach(num => {
  const index = arr1.indexOf(num);
  if (index !== -1) {
    arr1.splice(index, 1);
  }
});

console.log(arr1); // Output: [1, 3, 5]

In this example, we have the same two arrays: arr1 and arr2. We loop through each element of arr2 using the forEach() method. For each element, we find its index in arr1 using the indexOf() method. If the index is not -1 (i.e. the element is found in arr1), we use the splice() method to remove that element from arr1.

Method 3: Using reduce()

A third way to remove elements from an array is to use the reduce() method along with the includes() method. Here's an example:


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

const reducedArr = arr1.reduce((acc, num) => {
  if (!arr2.includes(num)) {
    acc.push(num);
  }
  return acc;
}, []);

console.log(reducedArr); // Output: [1, 3, 5]

In this example, we use the reduce() method to loop through each element of arr1 and accumulate a new array called reducedArr. For each element of arr1, we check whether it is included in arr2 using the includes() method. If it is not included, we push it to the acc array (which is the accumulator). Finally, we return the acc array from the reduce() method, which is the resulting array with all elements of arr2 removed from arr1.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe