4

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

1

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.