javascript - 如何比较javascript数组的内容,而不是它们的顺序?

标签 javascript arrays comparison

<分区>

正如标题所说,我想比较两个js数组,我只关心内容是否相同,但我不关心它们的顺序是否相同。所以我期望的是:

[1, 2, 3, 3] == [1, 2, 3, 3]     // True
[1, 2, 3, 3] == [1, 3, 2, 3]     // True
[1, 2, 3, 3] == [1, 2]           // False
[1, 2, 3, 3] == [1, 2, 3]        // False
[1, 2, 3, 3] == [1, 2, 3, 3, 3]  // False
[1, 2, 3, 3] == [1, "2, 3, 3"]      // False

显然比较运算符不起作用。来自 this SO answer我得到了下面的 Array.prototype 方法,但不幸的是,它也会检查顺序是否相同。

那么有人知道我如何检查两个 js 数组是否包含相同的元素,而不考虑元素的顺序吗?欢迎所有提示!

Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time 
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].equals(array[i]))
                return false;       
        }           
        else if (this[i] != array[i]) { 
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;   
        }           
    }       
    return true;
}   

最佳答案

比较前先排序

根据下面的评论,如果您希望 2 个 arr 包含不同的原始类型。请添加此排序函数。

function s(x,y){
    var pre = ['string' , 'number' , 'bool']
    if(typeof x!== typeof y )return pre.indexOf(typeof y) - pre.indexOf(typeof x);

    if(x === y)return 0;
    else return (x > y)?1:-1;

}
var arr1 = [1, 2, 3, 3].sort(s);
var arr2 = [1, 3, 2, 3].sort(s);

arr1.equals(arr2);// true

关于javascript - 如何比较javascript数组的内容,而不是它们的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29672847/

相关文章:

javascript - 确定中心

javascript - 度。轮流

javascript - 如何使用 React 映射对象数组的对象数组

javascript - 当后退按钮触发 popState 时,如何防止页面刷新?

javascript - 从外部脚本中的函数捕获错误

python - 如何在 Python 中构造具有多个特征的元素

arrays - 我如何在 Mongoose 中查询以获得 "answers"数组,其中 'objective'数组内的 'answers'是 "Awareness"

comparison - 如何比较两个ISO标准指纹模板?

python - 选择查询非常慢,我怎样才能加快速度?

xml - 在 Flash 中使用 json 而不是 xml 的任何特殊优势