Filter array based on another array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Therefore, the output should look like −

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[ 7, 6, 3, 6, 3 ]
raja
Published on 20-Oct-2020 12:06:49
Advertisements