JS中怎么判断两个数组是否包含的内容相同?

JS中判断数组是否包含相同内容,每个子元素内容相同,顺序不同也算相同,而且数组里的内容不只有基本类型,还可能有对象,看了网上很多方法,测试了一下,基本都不太对。。。

阅读 25.5k
5 个回答
http://underscorejs.org/#difference

difference_.difference(array, *others)
Similar to without, but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

if ( _.difference(arr1, arr2).length == 0 && _.difference(arr2, arr1).length == 0 ) {
  //两个数组相同, 数组元素有obj之类的不知行不行
}

可以使用es7数组新增的includes方法。遍历数组a, 然后看数组b是否includes
数组实例的includes

function isEquals(a, b) {
    return JSON.stringify(a.sort()) === JSON.stringify(b.sort());
}

改进算法

缺陷:比较数组的时候必须按顺序相等,因为数级里的 object 没法排序

const compare = (() => {
    function compareArray(a, b) {
        console.log("array", a, b);
        if (a.length !== b.length) {
            return false;
        }
        const length = a.length;
        for (let i = 0; i < length; i++) {
            if (!compare(a[i], b[i])) {
                return false;
            }
        }

        return true;
    }

    function compareObject(a, b) {
        console.log("object", a, b);
        const keya = Object.keys(a);
        const keyb = Object.keys(b);

        if (keya.length !== keyb.length) {
            return false;
        }

        return keya.every(key => {
            if (!compare(a[key], b[key])) {
                return false;
            }
            return true;
        });
    }

    function compare(a, b) {
        if (a === b) {
            return true;
        }

        if (typeof a !== typeof b || a === null || b === null) {
            return false;
        }

        if (Array.isArray(a)) {
            if (!Array.isArray(b)) {
                return false;
            }
            return compareArray(a, b);
        }

        if (typeof a === "object") {
            return compareObject(a, b);
        }

        console.log("value", a, b);
        return false;
    }

    return compare;
})();


var aa = [{ Name: "YuanXP", Id: 9 }, { Name: "YuanX", Id: 9 }];
var bb = [{ Name: "YuanXP", Id: 9 }, { Id: 9, Name: "YuanX" }];
var cc = [{ Name: "YuanXP", Id: 19 }, { Id: 9, Name: "YuanX" }];

console.log(compare(aa, bb));
console.log(compare(aa, cc));

连接两个数组,用hash判断重复

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题