Subtracting array in JavaScript Delete all those elements from the first array that are also included in the second array


Suppose, we have two arrays of literals like this −

const arr1 = ['uno', 'dos', 'tres', 'cuatro'];
const arr2 = ['dos', 'cuatro'];

We are required to write a JavaScript function that takes in two such arrays and delete all those elements from the first array that are also included in the second array.

Therefore, for these arrays, the output should look like this −

const output = ['uno', 'tres'];

Example

const arr1 = ['uno', 'dos', 'tres', 'cuatro'];
const arr2 = ['dos', 'cuatro'];
const findSubtraction = (arr1 = [], arr2 = []) => {
   let filtered = [];
   filtered = arr1.filter(el => {
       if(arr2.indexOf(el) === -1){
            return true;
      };
   });
   return filtered;
};
console.log(findSubtraction(arr1, arr2));

Output

And the output in the console will be −

[ 'uno', 'tres' ]

Updated on: 23-Nov-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements