2

i have an 2-dimensional array. for example

var bruecken = [[1,2],[3,4]];

now i am trying to test, if a subarray exists:

console.log(jQuery.inArray([1,2], bruecken));

or

console.log(bruecken.indexOf([1,2]));

but both ways it returns -1. what am i doing wrong?

hakre
  • 193,403
  • 52
  • 435
  • 836
losh
  • 23
  • 1
  • 3
  • possible duplicate of [Search multi-dimensional array JavaScript](http://stackoverflow.com/questions/8809425/search-multi-dimensional-array-javascript) – DrColossos Sep 05 '12 at 12:09
  • you know, you can upvote answers which you find helpful... ;-) – codebox Sep 05 '12 at 13:10

2 Answers2

2

The fastest way would be to use a for loop and compare them, then return if found. Here is something you can work with, I used JSON for comparison, but you can just use whatever comparator you find best (there are plenty):

function arrayInArray(needle, haystack) {
    var i=0, len=haystack.length, target=JSON.stringify(needle);
    for(; i<len; i++) {
        if (JSON.stringify(haystack[i]) == target) {
            return i;
        }
    }
    return -1;
}

arrayInArray( [0,1], [ [1,2], [0,1] ] ); // 1

If you want booleans, just return true instead of i and false instead of -1.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

I don't think inArray will work because comparing two identical arrays using == will return false. You could try using grep instead:

function subArrayInArray(subArray, array){
    var matches = $.grep(array, function(a){
        // Compare the target array with each of the child arrays
        return $(subArray).not(a).length == 0 && $(a).not(subArray).length == 0;
    });
    return !!matches.length;    
}

The method for comparing two arrays was stolen from this question

Community
  • 1
  • 1
codebox
  • 19,927
  • 9
  • 63
  • 81
  • thanks! thats what i need. could you please provide a sample code for a function like `inArray(matches, target)` that returns boolean? – losh Sep 05 '12 at 12:34
  • changed to function that returns boolean, as requested – codebox Sep 05 '12 at 13:06