我想比较两个数组。。。理想地、有效地。没有什么稀奇古怪的,如果它们是相同的,那就是真的,如果不是,那就是假的。毫不奇怪,比较运算符似乎不起作用。

var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2);    // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2));    // Returns true

JSON对每个数组进行编码,但是否有一种更快或“更好”的方法来简单地比较数组而不必遍历每个值?


当前回答

另一种代码很少的方法(使用Array reduce和Array includes):

arr1.length == arr2.length && arr1.reduce((a, b) => a && arr2.includes(b), true)

如果还要比较顺序的相等性:

arr1.length == arr2.length && arr1.reduce((a, b, i) => a && arr2[i], true)

长度检查确保一个数组中的元素集不仅仅是另一个数组的子集。缩减器用于遍历一个数组并搜索另一个数组中的每个项。如果找不到一项,reduce函数将返回false。在第一个示例中,正在测试是否包含元素第二个示例也检查订单

其他回答

在我的例子中,比较数组只包含数字和字符串。此函数将显示数组是否包含相同的元素。

function are_arrs_match(arr1, arr2){
    return arr1.sort().toString() === arr2.sort().toString()
}

让我们测试一下!

arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]

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

与嵌套数组一起使用MULTIPLE参数:

//:Return true if all of the arrays equal.
//:Works with nested arrays.
function AllArrEQ(...arrays){
    for(var i = 0; i < (arrays.length-1); i++ ){
        var a1 = arrays[i+0];
        var a2 = arrays[i+1];
        var res =( 
            //:Are both elements arrays?
            Array.isArray(a1)&&Array.isArray(a2) 
            ?
            //:Yes: Compare Each Sub-Array:
            //:v==a1[i]
            a1.every((v,i)=>(AllArrEQ(v,a2[i])))
            :
            //:No: Simple Comparison:
            (a1===a2)
        );;
        if(!res){return false;}
    };;
    return( true );
};;

console.log( AllArrEQ( 
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
));; 

这将比较2个未排序的数组:

function areEqual(a, b) {
  if ( a.length != b.length) {
    return false;
  }
  return a.filter(function(i) {
    return !b.includes(i);
  }).length === 0;  
}

使用数字/字符串/数组/对象的Ré草书cmp函数

<脚本>var cmp=函数(元素,目标){if(元素类型!==目标类型){return false;}否则if(typeof element==“object”&&(!target||!element)){返回目标==元素;}else if(元素类型==“对象”){var keys_element=对象.keys(元素);var keys_target=对象.keys(目标);如果(keys_element.length!==keys_target.length){return false;}其他的{对于(var i=0;i<keys_element.length;i++){如果(keys_element[i]!==keys_target[i])return false;if(!cmp(元素[keys_element[i]],目标[keys_target[i]]))return false;}返回true;}}其他的{返回元素==目标;}};console.log(cmp({键1:3,key2:“字符串”,key3:[4,“45”,{key4:[5,“6”,false,null,{v:1}]}]}, {键1:3,key2:“字符串”,key3:[4,“45”,{key4:[5,“6”,false,null,{v:1}]}]})); // 真的console.log(cmp({键1:3,key2:“字符串”,key3:[4,“45”,{key4:[5,“6”,false,null,{v:1}]}]}, {键1:3,key2:“字符串”,键3:[4,“45”,{键4:[5,“6”,未定义,null,{v:1}]}]})); // 假的</script>

我的解决方案比较对象,而不是数组。这将以与Tomáš相同的方式工作,因为数组是对象,但没有警告:

Object.prototype.compare_to = function(comparable){
    
    // Is the value being compared an object
    if(comparable instanceof Object){
        
        // Count the amount of properties in @comparable
        var count_of_comparable = 0;
        for(p in comparable) count_of_comparable++;
        
        // Loop through all the properties in @this
        for(property in this){
            
            // Decrements once for every property in @this
            count_of_comparable--;
            
            // Prevents an infinite loop
            if(property != "compare_to"){
                
                // Is the property in @comparable
                if(property in comparable){
                    
                    // Is the property also an Object
                    if(this[property] instanceof Object){
                        
                        // Compare the properties if yes
                        if(!(this[property].compare_to(comparable[property]))){
                            
                            // Return false if the Object properties don't match
                            return false;
                        }
                    // Are the values unequal
                    } else if(this[property] !== comparable[property]){
                        
                        // Return false if they are unequal
                        return false;
                    }
                } else {
                
                    // Return false if the property is not in the object being compared
                    return false;
                }
            }
        }
    } else {
        
        // Return false if the value is anything other than an object
        return false;
    }
    
    // Return true if their are as many properties in the comparable object as @this
    return count_of_comparable == 0;
}