0

如何检查第一个数组中的至少一个值是否存在于第二个数组中?例如,如何检查 car_1 数组和 car_2 数组上是否有 BMW?

var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
4

7 回答 7

2

使用一些完整的解决方案:

// will return true if at least one element of cars_1 is in cars_2
cars_1.some(function (e) {
    return cars_2.indexOf(e) >= 0;
});
于 2013-03-23T01:01:28.590 回答
2

一种快速简便的方法:

function overlap(arr1,arr2) {
  for(var i = 0; i < arr1.length; ++i)
    if(arr2.indexOf(arr1[i]) != -1)
      return true;
  return false;
}
于 2013-03-23T01:02:05.173 回答
1

一个快速简单的答案:

for (var i =0; i<cars_1.length; i++){
    for (var j=0; j<cars_2.length; j++){
        if(cars_2[j] == cars_1[i]) return true;
    }
}
return false;

编辑:好的,更有效地回应评论:) Edit2:好的,更高效:)

于 2013-03-23T01:02:07.763 回答
0

一个简单的 O(m+n) 解决方案:

var cars_1 = ["Saab","Volvo","BMW"];
var cars_2 = ["Honda","Mazda","BMW", "suzuki"];

// build up a hash table of the cars in the 1st sequence:
var set_1 = {};
for (var i = 0; i < cars_1.length; ++i) {
    set_1[cars_1[i]] = true;
}

// look if there is a car in sequence 2 that is in set_1:
var has_intersection = false;
for (var i = 0; i < cars_2.length; ++i) {
    if (set_1[cars_2[i]] === true) {
        has_intersection = true;
        break;
    }
}

也适用于任何浏览器。

于 2013-03-23T01:04:20.650 回答
0

如果您的浏览器支持它,您可以使用该.some方法。

var cars1 = [...],
    cars2 = [...];

var res = cars1.some(function(a) {
    return cars2.indexOf(a) > -1;
});

如果没有,那么您可以创建自己的 shim:

function some(list, callback) {
    var len = list.length;

    for (var i = len; i--;) {
        if (callback(list[i], i)) {
            return true;
        }
    }
    return false;
}

var res = some(cars1, function(a) {
    return cars2.indexOf(a) > -1;
});
于 2013-03-23T01:04:53.163 回答
0

您还可以使用“过滤器”方法:

    var cars_1 = new Array("Saab","Volvo","BMW");
    var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
    var cars_3 = new Array("Audi");
    
    /* with underscore.js */
    var _hasIntersection = function (arr1, arr2) {
        var intArr = _.filter(arr1, function (elem) { return arr2.indexOf(elem) > -1 });
        return intArr.length;
    }
    
    /* or using Array.prototype.filter */
    var hasIntersection = function (arr1, arr2) {
        var intArr = arr1.filter(function (elem) { return arr2.indexOf(elem) > -1 });
        return intArr.length;
    }
    
    console.log(_hasIntersection(cars_1, cars_2)); // 1
    console.log(hasIntersection(cars_1, cars_2)); // 1
    console.log(hasIntersection(cars_1, cars_3)); // 0
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

于 2014-09-25T09:14:28.690 回答
-3

有几种方法可以做到这一点:

指数()

var cars_1 = ["Saab","Volvo","BMW"];
var cars_2 = ["Honda","Mazda","BMW", "suzuki"];

cars_1.indexOf("BMW") != -1
// true
于 2013-03-23T00:58:32.220 回答