Deviations in two JavaScript arrays in JavaScript

We have two arrays of numbers like these −

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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

Output

The output in the console will be −

[ 6, 5, 1 ]