How to detect array equality in JavaScript?

后端 未结 4 1442
一个人的身影
一个人的身影 2020-12-16 19:21

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

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


        
相关标签:
4条回答
  • 2020-12-16 19:49

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

    var equal = array1.compareArrays(array2);
    
    0 讨论(0)
  • 2020-12-16 19:59

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

    0 讨论(0)
  • 2020-12-16 19:59

    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.

    0 讨论(0)
  • 2020-12-16 20:04
    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.

    0 讨论(0)
提交回复
热议问题