如何比较javascript数组的内容,而不是它们的顺序? [英] How to compare contents of javascript array, but not the order of them?

查看:97
本文介绍了如何比较javascript数组的内容,而不是它们的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As the title says I want to compare two js arrays in which I only care about the contents being the same, but I don't care about the order of them being the same. So what I would expect is this:

[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

显然,比较运算符不起作用。从这个SO答案,我得到了下面的Array.prototype方法,但不幸的是,该方法还检查顺序是否相同。

Obviously the comparison operator doesn't work. From this SO answer I got the Array.prototype method below, but that unfortunately also checks if the order is the same.

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

So does anybody know how I can check if two js arrays contain the same elements, not taking into account the order of the elements? All tips are welcome!

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;
}   


推荐答案

在比较之前对它们进行排序:

sort them before comparing:

从下面的注释中,如果您希望2个arrs包含不同的原始类型,请添加此排序函数。

from the comment below, if you want the 2 arrs to contain different primitive type.add this sort function.

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数组的内容,而不是它们的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆