# Finding the difference between two arrays - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

## 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 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

This will produce the following output in console −

[ 6, 5, 1 ]
Published on 18-Sep-2020 16:04:55