Remove elements from array using JavaScript filter - JavaScript


Suppose, we have two arrays of literals like these −

const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];

We are required to write a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array.

And then return the filtered array to get the below output −

const output = [7, 6, 3, 6, 3];

Example

Following is the code −

const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];
const filterArray = (arr1, arr2) => {
   const filtered = arr1.filter(el => {
      return arr2.indexOf(el) === -1;
   });
   return filtered;
};
console.log(filterArray(arr1, arr2));

Output

This will produce the following output in console −

[ 7, 6, 3, 6, 3 ]

Updated on: 18-Sep-2020

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements