43

在 JavaScript 中,如何测试一个数组是否包含另一个数组的元素?

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

5 回答 5

83

没有 set 函数可以做到这一点,但您可以简单地做一个临时数组交集并检查长度。

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

一种更有效的方法是使用.everywhich 将在虚假情况下短路。

arr1.every(elem => arr2.indexOf(elem) > -1);
于 2013-03-20T03:53:07.053 回答
22

您可以使用array.indexOf()

伪代码:

function arrayContainsAnotherArray(needle, haystack){
  for(var i = 0; i < needle.length; i++){
    if(haystack.indexOf(needle[i]) === -1)
       return false;
  }
  return true;
}
于 2013-03-20T03:53:13.057 回答
4
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

     }

}
于 2013-03-20T04:48:50.273 回答
4

ES6 解决方案使用includes

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

与上面的 Explosion Pills 的解决方案非常相似,只是更具可读性(并且可以说是慢了一点点)。

于 2020-06-30T07:39:22.477 回答
0

I faced the same case if I got you exactly, my case was to check visited places while one trip, every trip have its own point and we have a data for all working area places, here is the code maybe help you.

https://stackblitz.com/edit/trips-calculator?file=index.js

于 2020-10-23T23:08:47.437 回答