如何知道两个数组是否具有相同的值 [英] How to know if two arrays have the same values

查看:44
本文介绍了如何知道两个数组是否具有相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个数组:一个填充来自 ajax 请求的信息,另一个存储用户点击的按钮.我使用此代码(我填写了示例编号):

I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):

var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
    doSomething();
}else{
    doAnotherThing();
}

但它总是给出false,即使两个数组相同,但名称不同.(我在 Chrome 的 JS 控制台中检查了这个).那么,有什么办法可以知道这两个数组是否包含相同的内容?为什么它给出 false?我怎么知道第一个数组中的哪些值不在第二个数组中?

But it always gives false, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false? How can I know which values in the first array are not in the second?

推荐答案

对数组进行排序并一一比较它们的值.

Sort the arrays and compare their values one by one.

function arrayCompare(_arr1, _arr2) {
    if (
      !Array.isArray(_arr1)
      || !Array.isArray(_arr2)
      || _arr1.length !== _arr2.length
      ) {
        return false;
      }
    
    // .concat() to not mutate arguments
    const arr1 = _arr1.concat().sort();
    const arr2 = _arr2.concat().sort();
    
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false;
         }
    }
    
    return true;
}

这篇关于如何知道两个数组是否具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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