JavaScript Compare Two Arrays for Unmatched

JavaScript compare two arrays for not matched; Through this tutorial, i am going to show you how to compare two ordered and unordered arrays in javascript and returning the differences.

Compare two arrays in javascript find differences

There are three solution for find the difference between two arrays in JavaScript:

Let’s you have two arrays; And want to compare two arrays in javascript find differences:

let arr1=  [1,10,11,12,15,100,5,6,7,5];
let arr2=  [1,10,11,12,15,100,50,60,70,50]; 

Solution 1 – Using array indexOf() and filter()

You can find the difference between two arrays using the array indexOf() and filter() method; as shown below:

let arr1=  [1,10,11,12,15,100,5,6,7,5];
let arr2=  [1,10,11,12,15,100,50,60,70,50];
let arrayDifference = arr1.filter(x => arr2.indexOf(x) === -1);
console.log(arrayDifference); // [5, 6, 7, 5]

Here, arr1 elements are compared in the second array, which are not present in the second array, it’s difference.

In this approach, we will compare the elements of the first array with the elements of the second array. And those not in the second array will be found in the output.

Solution 2 – Using array include() and filter()

You can use array include() method instead of array indexOf() to compare two arrays in javascript find differences; as shown below:

let arr1=  [1,10,11,12,15,100,5,6,7,5];
let arr2=  [1,10,11,12,15,100,50,60,70,50];
let arrayDifference = arr1.filter(x => !arr2.includes(x));
console.log(arrayDifference); //[5, 6, 7, 5]

Approach 3: Using split(), indexOf(), sort(), map(), push()

Using some array built-in method like split(), indexOf(), sort(), toString and map(), push() to compare the first array from the second and the second array from the first, get the difference which is not the same in both arrays.

See the following example:

let arr1=  [1,10,11,12,15,100,5,6,7,5];
let arr2=  [1,10,11,12,15,100,50,60,70,50];
 function arrayDifference(arr1, arr2) {
    var arr = [];
    arr1 = arr1.toString().split(',').map(Number);
    arr2 = arr2.toString().split(',').map(Number);
    // for array1
    for (var i in arr1) {
       if(arr2.indexOf(arr1[i]) === -1)
       arr.push(arr1[i]);
    }
    // for array2
    for(i in arr2) {
       if(arr1.indexOf(arr2[i]) === -1)
       arr.push(arr2[i]);
    }
    return arr.sort((x,y) => x-y);
 }
console.log(arrayDifference(arr1, arr2)); // [5, 5, 6, 7, 50, 50, 60, 70]

Here, in third approach, both compare the arrays. And the elements which are not in both the arrays are the difference at the compare.

Recommended JavaScript Tutorials

Recommended:-JavaScript Arrays

Leave a Comment