在JavaScript/CoffeeScript中判断一个数组是否包含另一个数组的内容

Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

本文关键字:数组 是否 一个 包含 另一个 CoffeeScript JavaScript 判断      更新时间:2023-09-26

在JavaScript中,我如何测试一个数组有另一个数组的元素?

arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true

没有set函数可以做到这一点,但是您可以简单地做一个特别的数组相交并检查长度。

[8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {
    return arr1.indexOf(elem) > -1;
}).length == arr1.length

更有效的方法是使用.every,它会在错误的情况下短路。

arr1.every(elem => arr2.indexOf(elem) > -1);

可以使用array.indexOf():

伪代码:

function arrayContainsAnotherArray(needle, haystack){
  for(var i = 0; i < needle.length; i++){
    if(haystack.indexOf(needle[i]) === -1)
       return false;
  }
  return true;
}

使用includes的ES6解决方案:

[1].every(elem => [1,2,3].includes(elem));

与上面的爆破药丸的解决方案非常相似,只是更具可读性(并且可以说是稍微慢一点)。

function arr(arr1,arr2)
{
    for(var i=0;i<arr1.length;i++)
     {
        if($.inArray(arr1[i],arr2) ==-1)
               //here it returns that arr1 value does not contain the arr2
        else
             // here it returns that arr1 value contains in arr2
     }
}