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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 23-Nov-2020 06:27:12
Advertisements