检查其他数组中是否存在数组值

时间:2013-03-23 00:55:41

标签: javascript arrays

如何检查第二个数组中是否存在第一个数组中至少有一个值? 例如,我如何检查car_1阵列和car_2阵列上是否有宝马?

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

7 个答案:

答案 0 :(得分:2)

使用some完成解决方案:

// 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;
});

答案 1 :(得分: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: 好的,效率更高:)

答案 2 :(得分:0)

一种快捷简便的方法:

function overlap(arr1,arr2) {
  for(var i = 0; i < arr1.length; ++i)
    if(arr2.indexOf(arr1[i]) != -1)
      return true;
  return false;
}

答案 3 :(得分: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;
    }
}

也适用于任何浏览器。

答案 4 :(得分:0)

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

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

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

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

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;
});

答案 5 :(得分: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>

答案 6 :(得分:-2)

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

indexOf()

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

cars_1.indexOf("BMW") != -1
// true