简体   繁体   中英

How can I tell if a value in one array is equal to a value in another array in Javascript?

In Javascript, I have 2 arrays of 15 string elements, each of 0 to 17 characters.

How can I tell if one of the values of the first of these two arrays has a value equal to one of the values of the second array?

Example:

var array1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'];
var array2 = ['z','z','z','z','z','z','z','z','z','z','z','z','z','o','z'];
myFunction(array1,array2); // returns false

Example 2:

var array1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','s'];
var array2 = ['z','z','z','z','z','z','z','z','z','z','z','z','z','o','z'];
myFunction(array1,array2); // returns true

Assuming dbaupp is right and you have a typo, you want to find the intersection of the two arrays and see if it is non-empty.

The intersection of two sets means the set of elements that both original sets have in common. If there is at least one element in common, the intersection will be non-empty.

To do that, see

Simplest code for array intersection in javascript

This code checks if the two lists have a common element, which is done by sorting the lists and then stepping through them together, advancing whichever list is "behind".

function(list1, list2) {
    var l1 = list1.sort(), l2 = list2.sort(),
        len1 = l1.length, len2 = l2.length,
        i1 = 0, i2 = 0;

    while (i1 < len1 && i2 < len2) {
        if (l1[i1] == l2[i2])
            return true;

        if (l1[i1] < l2[i2])
            i1++;
        else
            i2++;
    }
    return false;
}

NB. as Eric said you could also just intersect the two lists, and check that the resulting list is non-empty, but this code here will be more efficient since it doesn't have to generate a whole new list, nor does it have to go through all of both lists if there is a common element.

Eric J.'s suggestion of an intersection is probably most elegant way to approach the problem.

A straightforward translation of what you're asking could work like this:

function containsAny(array1, array2) {
  for (var i=0; i<array1.length; i++) {
      for (var j=0; j<array2.length; j++) {
          if (array1[i] == array2[j]) return true;
      }
  }
  return false;
}

var array1 = ['a','b','c'];
var array2 = ['1','2','3'];
var array3 = ['a','b','2'];

containsAny(array1, array2); // returns false
containsAny(array2, array3); // returns true 
containsAny(array1, array3); // returns true

Ok, assuming I'm understanding your problem correctly, I tossed together a Fiddle that will match the elements of 2 arrays using the JQuery 'each' method:

http://jsfiddle.net/phillipkregg/Ug3DM/1/

var array1 = ["a","b","c","o"];
var array2 = ["z","z","b","z","z","o"];

array1.each(function(item){
    var element = item;        
    var match = [];
    array2.each(function(item2) {
        if (item2 === element)
        {
            match.push(item2); 
            alert(match);

        }            
    });                   
});​

Maybe that will get you started.

I try to use the 'each' method upstairs, but it seems not work, while 'each' is used for objects, not for array. so I change the code.

var array1 = ["a","b","c","o"];
var array2 = ["z","z","b","z","z","o"];
var match = [];
$.each(array1, function(key, val){
var element = val;
    $.each(array2, function(key, val){
    if(element === val)
    {
    match.push(val);
    }
    });
});
$.each(match, function(key, val){
    alert(key+'--'+val);
});

Most browsers use builtin indexOf and filter methods of Arrays, if you use these methods often you can conditionally add them to older browsers.

var array1= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 's'];
var array2= ['z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'o', 'z'];
var array3= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'o', 'k', 'l', 'm', 'n', 's'];


1. array1.inCommon(array2)>>
(array length 0)

2. array2.inCommon(array3)>>
(array length 1)
o

3. array3.inCommon(array1)>>
(array length 14)
a, b, c, d, e, f, g, h, i, k, l, m, n, s



Array.prototype.inCommon= function(ar){
    return this.filter(function(itm){
        return ar.indexOf(itm)!= -1;
    });
}

Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    if(typeof i!= 'number') i= 0;
    var L= this.length;
    while(i< L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i< L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM