4

The title should explain my question.

I have an array:

a = [[1,2],[1,3],[1,4]]; 

How can I check if the array [1,2] is inside the array a?

2

5 Answers 5

2

That depends on the situation.

given

var a = [1,2], b = [1,3], c = [a,b]; 

We can check easily if a resides in c, if we have c to test on.

for(var i=0,d;d=c[i];i++) { if(d === a) { //a is inside c } } 

or even simpler for browser that supports it (ie7 doesn't)

if(c.indexOf(a) != -1) { //a is inside c } 

But if we only have a, and a is not a local variable and we wish to know if it exists inside any array, then we can't, since a is a reference to an object and we can't possibly know if a reference to it exists elsewhere outside our current scope.

    1

    if you have a reference, the you can use the == operator. else you have to write your own method to test values. something like this:

    function someMethod(testArr, wanted){ for (i=0; i<testArr.length; i++){ if(array_diff(testArr[i], wanted).length==0 && array_diff(wanted, $subArr).length==0){ return true; } } return false; } function array_diff(a1, a2) { var a=[], diff=[]; for(var i=0;i<a1.length;i++) a[a1[i]]=true; for(var i=0;i<a2.length;i++) if(a[a2[i]]) delete a[a2[i]]; else a[a2[i]]=true; for(var k in a) diff.push(k); return diff; } 
    3
    • 2
      this is php, he asked about javascript
      – Ali
      CommentedOct 8, 2011 at 13:56
    • I would re-think your answer as to not receive more down votes. He asked for javascript not php.
      – brenjt
      CommentedOct 8, 2011 at 14:04
    • sorry, I confused it with another question. i corrected it to javascript. :)CommentedOct 8, 2011 at 14:47
    0

    If your array contains numbers or texts only, you can join each array into string, then compare if a string is inside the other.

    var a = [[1,2],[1,3],[1,4]]; var b = [1,2] var aStr = '@' + a.join('@') + '@' var bStr = '@' + b.join() + '@' if (aStr.indexOf(bStr) > -1){ alert ('b is inside a') }else{ alert ('b is not inside a') } 
      0

      You can try this if your array elements are non-nested arrays.

      return JSON.stringify([[1,2],[1,3],[1,4]]).indexOf(JSON.stringify([1,2])) > 0 

      This checks if the JSON representation of [1,2] is contained in the JSON representation of [[1,2],[1,3],[1,4]]

      But in this case it gives a false positive

      return JSON.stringify([[[1,2]],[1,3],[1,4]]).indexOf(JSON.stringify([1,2])) > 0 

      returns true.

        0

        You can also loop through the array object and for each of it's item you can use jQuery.isArray() to determine if the object is an array.

          Start asking to get answers

          Find the answer to your question by asking.

          Ask question

          Explore related questions

          See similar questions with these tags.