views:

60

answers:

3

How can I check if an array exists in an array of arrays ? I have tried either plain javascript and jquery methods but none seems to help.

IE this doesn't work:

$.inArray( [1,2], [[0], [], [1,2]] )

Even a more simple one:

[1,2] == [1,2] //gives false.
[1,2] === [1,2] //gives false.

ORDER is NOT important for my task, only same elements existing is neccesary.

+1  A: 

I guess to compare arrays are equal or not, you have to compare on individual elements and cannot compare arrays directly. i.e. You can loop through one of them and check if each element i.e. 1 or 2 is present in another array in which you are comparing i.e. [1,2].

Sachin Shanbhag
+4  A: 

In objects (and arrays are objects), to compare equality you have to check each member.

function arraysAreEqual(a, b) {
    if (a.length != b.length) return false;
    for (i = 0, l = a.length; i < l; ++i) {
        if (a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

You could make that a bit smarter to recursive search through nested arrays, but you get the idea.

nickf
+2  A: 
var arr = [[0], [], [1,2]];
var needle = [1, 2];
var i, entry, position = -1;

for(i = 0; entry = arr[i]; i++) {
    if(entry.toString() == needle.toString()){
        position = i;
        break;
    }
}
//position = 2

edit: this also works for nested arrays

I.devries