An array exists in an array of arrays

How to check if an array exists in an array of arrays? I tried using simple javascript and jquery methods, but no one helps.

IE this does not work:

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

Even simpler:

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

ORDER is NOT important to my task, only the same elements are needed.

+4
source share
3 answers

In objects (and arrays there are objects), in order to compare equality, you must 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 can make it a little smarter for recursively searching through nested arrays, but you get this idea.

+4
source
 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

+2
source

I think that comparing arrays is equal or not, you must compare individual elements and cannot compare arrays directly. those. you can skip one of them and check if each element is present, for example 1 or 2, in another array in which you are comparing, that is [1,2].

+1
source

All Articles