0

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
aaaidan
  • 7,093
  • 8
  • 66
  • 102
JavaAndCSharp
  • 1,507
  • 3
  • 23
  • 47
  • 2
    In your second example there doesn't appear to be a common element (should the `s` be an `o`?). – huon Mar 29 '12 at 01:10
  • 2
    i don't get the logic of the z's and letters. can you explain? – Joseph Mar 29 '12 at 01:12
  • @dbaupp: that's why the code returns false for the first example and true for the second one. – JavaAndCSharp Mar 29 '12 at 01:15
  • @Joseph: The z s and the letters are the 16 strings in each of the arrays. – JavaAndCSharp Mar 29 '12 at 01:16
  • There is a shared element in the first one but there isn't in the second, so you are actually asking for code that tells you if the two lists have *no* values that are equal? – huon Mar 29 '12 at 01:23
  • 1
    Shouldn't this be tagged `homework`? Or is this really an actual problem you are trying to solve? – gilly3 Mar 29 '12 at 01:25
  • I think the homework tag is discouraged these days. But if this is a homework question, it should say so in the question itself. http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions – aaaidan Mar 29 '12 at 01:48
  • @gilly3: It isn't homework, but it's funny you said that because it has to do with a homework-related webapp. Yes, it is an actual problem I want to solve. Yes, I'm really **that** bad at coding. – JavaAndCSharp Mar 29 '12 at 02:03

6 Answers6

1

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

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • 1
    So... I guess that means that this question is a duplicate. Is it? – JavaAndCSharp Mar 29 '12 at 01:17
  • 1
    Not exactly... your question was about how to find if there is a common element. One (good) answer is to find the intersection of the two lists. The question I reference tells how to find the intersection of two lists, but doesn't directly answer your original question. – Eric J. Mar 29 '12 at 01:22
  • Technically a duplicate, but not in spirit I think. Something tells me that OP doesn't think in terms of set theory, even if this is the best way to solve the problem... – aaaidan Mar 29 '12 at 01:33
1

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.

huon
  • 94,605
  • 21
  • 231
  • 225
1

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
aaaidan
  • 7,093
  • 8
  • 66
  • 102
  • Straightforward, yes, but performs O(N-squared). That fact is probably irrelevant, though, for the array sizes the OP is interested in. – Eric J. Mar 29 '12 at 01:24
  • Accepted because it's the shortest, most readable, and I really don't need speed in this case. – JavaAndCSharp Mar 29 '12 at 03:19
  • Thanks! Although, if your example is correct, this function currently returns the exactly wrong answer (returns true if there's at least one element in common). – aaaidan Mar 29 '12 at 21:14
0

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.

PhillipKregg
  • 9,358
  • 8
  • 49
  • 63
0

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);
});
HaleDeng
  • 31
  • 4
0

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;
}
kennebec
  • 102,654
  • 32
  • 106
  • 127