I'm using JavaScript, and would like to check whether an array exists in an array of arrays.
Here is my code, along with the return values:
var myArr = [1,3];
var prizes = [[1,3],[1,4]];
prizes.indexOf(myArr);
-1
Why?
It's the same in jQuery:
$.inArray(myArr, prizes);
-1
Why is this returning -1 when the element is present in the array?
Worth noting:
aOA[i].sort().join(',') === a.sort().join(',')
is a useful way to check for arrays that contain the same values in the same order, but are references to different objects.array.slice(0)
creates a non-referential copy of the original 2D array.However, to create a copy of a 3D array
arrayOfArrays.slice(0)
does not work; the reference chain will still be present. In order to create a non-referential copy the.map
function is necessary.If you don't create these non-referential array copies you can really run into some tough to track down issues. This function should operate as a conditional and not effect the initial objects passed in.
Javascript is one fickle mistress.
first define a compare function for arrays
second just find the array with
NOTE: check the browser compatibility for array.filter
You could iterate the array of arrays with
Array#some
and then check every item of the inner array with the single array withArray#every
.You can use this
then you can do just an indexOf() to check if it is present
Assuming you are only dealing with a two-dimensional array (you mention an "array of arrays" but nothing deeper than that), this non-recursive code should do what you need.
JSFiddle: http://jsfiddle.net/guypursey/V7XpE/. (View the console to see the result.)
Because
[1,3] !== [1,3]
, since objects will only equal if they reference the same object. You need to write your own search routine:References