如何检查第一个数组中的至少一个值是否存在于第二个数组中?例如,如何检查 car_1 数组和 car_2 数组上是否有 BMW?
var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
如何检查第一个数组中的至少一个值是否存在于第二个数组中?例如,如何检查 car_1 数组和 car_2 数组上是否有 BMW?
var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
使用一些完整的解决方案:
// 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;
});
一种快速简便的方法:
function overlap(arr1,arr2) {
for(var i = 0; i < arr1.length; ++i)
if(arr2.indexOf(arr1[i]) != -1)
return true;
return false;
}
一个快速简单的答案:
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:好的,更高效:)
一个简单的 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;
}
}
也适用于任何浏览器。
如果您的浏览器支持它,您可以使用该.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;
});
您还可以使用“过滤器”方法:
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>
有几种方法可以做到这一点:
var cars_1 = ["Saab","Volvo","BMW"];
var cars_2 = ["Honda","Mazda","BMW", "suzuki"];
cars_1.indexOf("BMW") != -1
// true