Find the Symmetric difference between two arrays - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

In Mathematics, the symmetric difference of two sets, say A and B is represented by A △ B

And it is defined as the set of all those elements which belongs either to A or to B but not to both.

For example −

const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];

Then the symmetric difference of A and B will be −

const diff = [2, 4, 9]

Example

Following is the code −

const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      if(arr2.indexOf(arr1[i]) !== -1){
         continue;
      };
      res.push(arr1[i]);
   }
   for(let i = 0; i < arr2.length; i++){
      if(arr1.indexOf(arr2[i]) !== -1){
         continue;
      };
      res.push(arr2[i]);
   };
   return res;
};
console.log(symmetricDifference(A, B));

Output

This will produce the following output in console −

[2, 4, 9]
raja
Published on 30-Sep-2020 17:48:44
Advertisements