Program to find uncommon elements in two arrays - JavaScript



Let’s say, we have two arrays of numbers βˆ’

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both.

Let’s write the code for this function βˆ’

Example

Following is the code βˆ’

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const unCommonArray = (first, second) => {
   const res = [];
   for(let i = 0; i < first.length; i++){
      if(second.indexOf(first[i]) === -1){
         res.push(first[i]);
      }
   };
   for(let j = 0; j < second.length; j++){
      if(first.indexOf(second[j]) === -1){
         res.push(second[j]);
      };
   };
   return res;
};
console.log(unCommonArray(arr1, arr2));

Output

Following is the output in the console βˆ’

[ 6, 5, 1 ]
Updated on: 2020-09-14T14:07:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements