JQuery检查两个数组是否至少有一个公共元素

时间:2015-11-01 11:17:15

标签: jquery

我想用JQuery检查两个数组是否至少有一个公共元素并返回true。以下行无法正常工作:

 if(jQuery.inArray(array1,array2) > -1) {return true;}

请你帮我找到解决方案。

4 个答案:

答案 0 :(得分:3)

这样做的一种方法是遍历一个数组并使用$ .inArray作为第二个数组..

function hasCommonElement(arr1,arr2)
{
   var bExists = false;
   $.each(arr2, function(index, value){

     if($.inArray(value,arr1)!=-1){
        console.log(value);
        bExists = true;
     }

     if(bExists){
         return false;  //break
     }
   });
   return bExists;
}

jSfiddle

现在我们可以检查

if(hasCommonElement(arr1,arr2)){
    return true;
}

希望有更好的答案......

答案 1 :(得分:3)

我建议用简单的JavaScript:

// naming the function, defining the
// arguments to pass:
function commonElements(arr1, arr2) {

    // iterating over arr1, using
    // Array.prototype.some() wherein
    // 'el' is the current element of
    // the array over which we're iterating:
    return arr1.some(function (el) {

        // finding the 'el' value in
        // arr2; and comparing the index
        // if the 'el' value isn't found
        // in arr2 it returns -1:
        return arr2.indexOf(el) > -1;
    });
}

var one = [1, 2, 3, 4, 5],
    two = [5, 6, 7, 8, 9];

console.log(commonElements(one, two)); // true

function commonElements(arr1, arr2) {
  return arr1.some(function(el) {
    return arr2.indexOf(el) > -1;
  });
}

var one = [1, 2, 3, 4, 5],
  two = [5, 6, 7, 8, 9];

console.log(commonElements(one, two));

JS Fiddle

或者,可以重写以上内容以扩展Array的原型:

// extending the prototype of the Array,
// with a named method/function:
Array.prototype.commonElements = function (arr2) {

    // iterating over the 'this' array:
    return this.some(function (el) {

        // looks for the array-value
        // represented by 'el', and
        // comparing the returned index
        // to see if it's greater than
        // -1 (and so is found in 'this' array):
        return arr2.indexOf(el) > -1;
    });
}

var one = [1, 2, 3, 4, 5],
    two = [5, 6, 7, 8, 9];

console.log(one.commonElements(two)); // true

Array.prototype.commonElements = function(arr2) {
  return this.some(function(el) {
    return arr2.indexOf(el) > -1;
  });
}

var one = [1, 2, 3, 4, 5],
  two = [5, 6, 7, 8, 9];

console.log(one.commonElements(two));

JS Fiddle

答案 2 :(得分:1)

我真的很喜欢check if an array contains any elements in another array in Javascript问题的答案,尤其是代码:

Array.prototype.indexOfAny = function (array) {
    return this.findIndex(function(v) { return array.indexOf(v) != -1; });
}

Array.prototype.containsAny = function (array) {
    return this.indexOfAny(array) != -1;
}

然后你可以写:

needle = ['banana', 'apple', 'berry'];
haystack = ['tree', 'chest', 'apple'];

haystack.containsAny(needle); // return true

答案 3 :(得分:0)

使用某些方法更简单的方法

var needle = ['banana', 'apple', 'berry']; var haystack = ['tree', 'chest', 'apple']; needle.some(n => haystack.some(h=> h===n)); // returns true