10

There are two arrays in JavaScript, they are both in the following format:

[{'drink':['alcohol', 'soft', 'hot']}, {'fruit':['apple', 'pear']}];

I need to detect if the two arrays are equal or not. they are considered equal if they contain the same elements in a different order. How can I make that?

Mark Walters
  • 12,060
  • 6
  • 33
  • 48
David
  • 2,691
  • 7
  • 38
  • 50
  • Would you consider them equal if they contain the same elements in a different order, or do they have to be identical to both content and order? Is case important? – Sparky Sep 29 '11 at 07:04
  • Do you mean also checking different ordering recursively? If second array is `[{'fruit':['pear', 'apple']}, {'drink':['alcohol', 'hot', 'soft']}]` as elements is considered equal to the array you've shown? (note the pear/apple exchange) – 6502 Sep 29 '11 at 07:13
  • Is case important, i.e. should pear and PEAR be considered the same? – Sparky Sep 29 '11 at 07:18
  • possible duplicate of [how to check javascript array equals?](http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals) – Felix Kling Sep 29 '11 at 08:04
  • possible duplicate of [How to know if two arrays have the same values](http://stackoverflow.com/questions/6229197/how-to-know-if-two-arrays-have-the-same-values) – Palec Jun 24 '14 at 14:35

4 Answers4

6
  1. Check the length of both arrays
  2. Loop through the first array, compare each variable to the second array.

If 1 and 2 are both the same, your array is equal.

Function to compare objects/arrays:

Looping through true arrays can be achieved through for(var i=0; i<array.length; i++).
Walking through the properties of such an object can be done by for(var i in object).

function recursiveCompare(obj, reference){
    if(obj === reference) return true;
    if(obj.constructor !== reference.constructor) return false;
    if(obj instanceof Array){
         if(obj.length !== reference.length) return false;
         for(var i=0, len=obj.length; i<len; i++){
             if(typeof obj[i] == "object" && typeof reference[j] == "object"){
                 if(!recursiveCompare(obj[i], reference[i])) return false;
             }
             else if(obj[i] !== reference[i]) return false;
         }
    }
    else {
        var objListCounter = 0;
        var refListCounter = 0;
        for(var i in obj){
            objListCounter++;
            if(typeof obj[i] == "object" && typeof reference[i] == "object"){
                if(!recursiveCompare(obj[i], reference[i])) return false;
            }
            else if(obj[i] !== reference[i]) return false;
        }
        for(var i in reference) refListCounter++;
        if(objListCounter !== refListCounter) return false;
    }
    return true; //Every object and array is equal
}

If you don't understand the function, feel free to request an explanation at the comments.

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • @Sparky Good point. I've reversed the order of the notes. I've also updated my answer, and included a comparison function. – Rob W Sep 29 '11 at 07:23
  • 1
    The benefits of being old and programming when languages were a lot slower... – Sparky Sep 29 '11 at 07:24
  • Do you know you can compare arrays in Javascript? And know if they are bigger or smaller. – Mic Sep 29 '11 at 09:29
  • @Mic What do you mean? Have you actually read the question + answer? – Rob W Sep 29 '11 at 09:42
  • @Rob... I think so, did you check my answer below? Something wrong in it? – Mic Sep 29 '11 at 12:27
  • Ah I see. Your Array compare function also returns true for `isSame([1,2], [2,1])`. The sequence of the elements is often important. Also, I've just benchmarked our functions, and my function is three times faster: http://jsfiddle.net/Kv383/1/. – Rob W Sep 29 '11 at 12:59
1

With Javascript, you can't check if arrays are equals, but you can compare them like this:

var arr1 = ['alcohol', 'soft', 'hot'],
    arr2 = ['apple', 'pear'],
    arr3 = ['soft', 'hot', 'alcohol'];

function isSame(a1, a2){
    return !(a1.sort() > a2.sort() || a1.sort() < a2.sort());
}

console.log( isSame(arr1, arr2) ); //false
console.log( isSame(arr1, arr3) ); //true

The sort put all elements in the same order, and if both < and > comparisons are false it means both are the same.

Mic
  • 24,812
  • 9
  • 57
  • 70
0

Does this answer your question? How to check if two arrays are equal with JavaScript?

var equal = array1.compareArrays(array2);
Community
  • 1
  • 1
JavaJens
  • 360
  • 1
  • 3
  • 14
  • It gives me "compareArrays" is not a function. – ArchNoob Nov 05 '17 at 20:59
  • This isn't great because compareArrays is not a defined built-in function in Javascript and it's not great practice to much around with the prototype of something as fundamental as the Array class. – Zack Dec 12 '20 at 09:55
0

You can try this JSON.stringify(array1)===JSON.stringify(array2); if you want the order also to be identical in both the arrays.

Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43