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

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


当前回答

本着原问题的精神:

我想比较两个数组。。。理想地、有效地。没有什么想象,如果它们是相同的,则为真,如果不是,则为假。

我一直在对这里提出的一些更简单的建议进行性能测试,结果如下(从快到慢):

而Tim Down(67%)

var i = a1.length;
while (i--) {
    if (a1[i] !== a2[i]) return false;
}
return true

每(69%)用户2782196

a1.every((v,i)=> v === a2[i]);

DEI减少(74%)

a1.reduce((a, b) => a && a2.includes(b), true);

Gaizka Allende&vivek的join&toString(78%)

a1.join('') === a2.join('');

a1.toString() === a2.toString();

Victor Palomo创作的半到字符串(90%)

a1 == a2.toString();

radtek的stringify(100%)

JSON.stringify(a1) === JSON.stringify(a2);

注意,下面的示例假设数组是排序的,一维数组。对于一个常见的基准测试,长度比较已被删除(将a1.length==a2.length添加到任何建议中,您将获得约10%的性能提升)。选择最适合您的解决方案,了解每种解决方案的速度和局限性。

其他回答

我的解决方案比较对象,而不是数组。这将以与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;
}

使用数字/字符串/数组/对象的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>

我知道JSON.stringfy在处理大型数据集时速度很慢,但如果使用模板文字呢?

例子:

const a = [1, 2, 3];
const b = [1, 2, 'test'];

const a_string = Array.isArray(a) && `${a}`;
const b_string = Array.isArray(b) && `${b}`;

const result = (a === b);

console.log(result);

当然,考虑到您正在使用ES6。

=)

您可以简单地使用lodash库中的isEqual。它非常高效和干净。

import isEqual from "lodash/isEqual";

const isTwoArraysEqual = isEqual(array1, array2);

我会这样做:

[2,3,4,5] == [2,3,4,5].toString()

当您使用“==”运算符时,javascript检查值(左侧和右侧)是否是相同的类型,如果是不同的,javascript尝试将两边转换为相同的类型。

Array == String

Array具有toString方法,因此javascript使用它将它们转换为相同的类型,工作方式如下:

[2,3,4,5].toString() == [2,3,4,5].toString()