How to detect array equality in JavaScript?

后端 未结 4 1465
一个人的身影
一个人的身影 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: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.

提交回复
热议问题