Finding deviations in two Number arrays in JavaScript


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

For example, if the two arrays are −

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

Output

Then the output should be −

const output = [ 6, 5, 12, 1, 34 ]

Example

The code for this will be −

const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const deviations = (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(deviations(arr1, arr2));

Output

The output in the console −

[6, 5, 12, 1, 34 ]

Updated on: 14-Oct-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements