Difference between two arrays in JavaScript
In this tutorial, we are going to learn about how to get a difference between two arrays in JavaScript with the help of examples.
Consider we have two arrays like this.
const arr1 = [1,2,3,4];
const arr2 = [1,2,4,5];
The difference between the above two arrays is [3,5]
.
Let’s write the solution in JavaScript with the help of es6 filter()
and includes()
method.
function getDifference(arr1,arr2){
return arr1
// filtering difference in first array with second array
.filter(x => !arr2.includes(x))
// filtering difference in second array with first array
.concat(arr2.filter(x => !arr1.includes(x)));
}
const arr1 = [1,2,3,4];
const arr2 = [1,2,4,5];
getDifference(arr1,arr2); // [3,5]
Explanation
In the above code, we have first filtered the difference in the first array with the second array using filter
and includes
method then we chained with the concat
method.
Inside the concat()
method we have filtered the difference in the second array with the first array.