How to compare two arrays using Javascript and get unmacthed elements?


Hi, I need to compare two arrays using javascript or jQuery and then get distinct values from each of them, like for example:

var arr1=["A","B","C"];
var arr2=["C","B","D"];

//get D by comparing above two arrays

How can i compare arrays and get distinct values from it?

Also, if both are identical (No different data), show a message like "Both values are same".


Asked by:- jaiprakash
0
: 1118 At:- 12/10/2017 2:00:37 PM
javascript arrays compare-arrays-values






2 Answers
profileImage Answered by:- pika

Two compare two javascript arrays you can create a helper function

var isEqual = function (value, other) {

    // Get the value type
    var type = Object.prototype.toString.call(value);

    // If the two objects are not the same type, return false
    if (type !== Object.prototype.toString.call(other)) return false;

    // If items are not an object or array, return false
    if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false;

    // Compare the length of the length of the two items
    var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
    var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
    if (valueLen !== otherLen) return false;

    // Compare two items
    var compare = function (item1, item2) {

        // Get the object type
        var itemType = Object.prototype.toString.call(item1);

        // If an object or array, compare recursively
        if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
            if (!isEqual(item1, item2)) return false;
        }

        // Otherwise, do a simple comparison
        else {

            // If the two items are not the same type, return false
            if (itemType !== Object.prototype.toString.call(item2)) return false;

            // Else if it's a function, convert to a string and compare
            // Otherwise, just compare
            if (itemType === '[object Function]') {
                if (item1.toString() !== item2.toString()) return false;
            } else {
                if (item1 !== item2) return false;
            }

        }
    };

    // Compare properties
    if (type === '[object Array]') {
        for (var i = 0; i < valueLen; i++) {
            if (compare(value[i], other[i]) === false) return false;
        }
    } else {
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (compare(value[key], other[key]) === false) return false;
            }
        }
    }

    // If nothing failed, return true
    return true;

};

You can compare arrays using the above function as below

var arr1 = [1, 2, 3, 4, 5];
var arr2 = [1, 2, 3, 4, 5];
 isEqual(arr1, arr2); //return true

Here is the complete fiddle to test different type of situations

Or if you want to check jquery version of this here is the fiddle link

Now once you know, if there is any difference element or not, you would have to loop through each element of both arrays to get unique data using javascript

Suppose you need to get a Unique data of array one from array2 for it code  will be

var array1 = ['11','12','13','14']

var array2 = ['11','13']
	

var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });

alert(array3);

output will be '12,14', working fiddle

2
At:- 12/14/2017 3:57:04 PM
thanks, not a perfect answer, but comparing arrays part helped me 0
By : jaiprakash - at :- 12/21/2017 7:18:38 AM


profileImage Answered by:- jaiprakash

Above answer is great for comparing two javascript arrays and difference.

I have found another way of getting different value of two arrays by comparing it,  here is the code for it.

function differenceOf2Arrays(arr1, arr2) {
    var temp = [];
    arr1 = arr1.toString().split(',').map(Number);
    arr2 = arr2.toString().split(',').map(Number);

    for (var i in arr1) {
        if (arr2.indexOf(arr1[i]) === -1) temp.push(arr1[i]);
    }
    for (i in arr2) {
        if (arr1.indexOf(arr2[i]) === -1) temp.push(arr2[i]);
    }
    return temp.sort((a, b) => a - b);
}

ES6 version of the above code

function differenceOf2Arrays(arr1, arr2) {
    const temp = [];
    arr1 = arr1.toString().split(',').map(Number);
    arr2 = arr2.toString().split(',').map(Number);

    for (var i in arr1) {
        if (!arr2.includes(arr1[i])) temp.push(arr1[i]);
    }
    for (i in arr2 ) {
        if (!arr1.includes(arr2[i])) temp.push(arr2[i]);
    }
    return temp.sort((a, b) => a - b);
}

You can call the above function as below

console.log(differenceOf2Arrays([1, 2, 3], [100, 2, 1, 10]));

output will be as below

[3,10,100]

Fiddle link https://jsfiddle.net/h1scen2y/1/

Source

1
At:- 3/8/2018 6:18:59 PM
I don't see much difference between ES6 version and plain javascript, just 'var' is converted into 'const', rest looks same, but still helpful answer, thanks 0
By : vikas_jk - at :- 5/3/2018 8:56:08 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly