Difference between first and the second array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two arrays of literals. The arrays might contain some identical entries as well.

The purpose of our function is to simply find out and return an array of all such elements that exists in the first array but not in the second.

Example

The code for this will be −

const arr1 = ['1', '2', '3', '4/2', '5/4', '6−2'];
const arr2 = ['1', '2', '3', '5/4', '4/2', '6−1', '7/2', '8−2'];
const differenceBetween = (arr1 = [], arr2 = []) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      const el = arr1[i];
      if(arr2.includes(el)){
         continue;
      };
      res.push(el);
   };
   return res;
};
console.log(differenceBetween(arr1, arr2));

Output

And the output in the console will be −

['6−2']
raja
Published on 23-Nov-2020 11:28:56
Advertisements