0

Example array:

var array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"];

Array with requires:

var array2 = ["d", "g", "j", "k"];

So it will return true if array1 contains at least one value from array2. Can you help me with that?

Note: array1 may contains all four values from array2.

Patrik Krehák
  • 2,595
  • 8
  • 32
  • 62
  • 1
    http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript – Arkar Aung Apr 09 '15 at 10:16
  • @ArkarAung it is similar and also it can solve my problem, but I wanted something simpler than your suggestion. Anyway, it doesn't work like I want, look here: http://jsfiddle.net/debute/vfse5ddu/ – Patrik Krehák Apr 09 '15 at 10:40

3 Answers3

4

You could try something as simple as:

function Contains(array1, array2)
{
    for(var i=0; i<array2.length; i++)
        if(array1.indexOf(array2[i])>-1)
            return true;

    return false;
}

Initially you loop through the items of array2. If one item of array2 is found in the array1 you return true. Otherwise you return false.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • `for (var item in array2)` is used with objects, not arrays. And `item` will be the keys, not the values. – Barmar Apr 09 '15 at 10:19
0
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;
Brian
  • 1,513
  • 2
  • 14
  • 17
0
var count = array2.length;

for (var i = 0; i < count; i++) {

    if (array1.indexOf(array2[i] !== -1) {
        return true;
    }

}
Vigneswaran Marimuthu
  • 2,452
  • 13
  • 16