Why does indexOf give -1 in this case:
var q = ["a","b"];
var matchables = [["a","b"],["c"]];
matchables.indexOf(q);
How should I establish if the value stored in q can be found in matchables?
Because indexOf uses === as the comparison flag.
=== operating on non-primitives (like Arrays) checks for if the Objects are identical. In JavaScript, Objects are only identical if they reference the same variable.
Try this to see what I mean (in console):
([])===([])
It returns false because they do not occupy the same space in memory.
You need to loop and use your own equality check for anything other than true/false/string primitive/number primitive/null/undefined
// Only checks single dimensional arrays with primitives as elements!
var shallowArrayEquality = function(a, b){
if(!(a instanceOf Array) || !(b instanceof Array) || a.length !== b.length)
return false;
for(var ii=0; ii<a.length; ii++)
if(a[ii]!==b[ii])
return false;
return true;
};
var multiDimensionalIndexOf = function(multi, single){
for(var ii=0; ii<a.length; ii++)
if(shallowArrayEquality(multi[ii], single) || multi[ii] === single)
return ii;
return -1;
};
multiDimensionalIndexOf(matchables, q); // returns 0
ii because it's easier to search against in codenon-literals? you probably mean non-primativesBecause
["a","b"] === ["a","b"]
is false.
The way to get it to work would Be this:
var q = ["a", "b"];
var matchables = [q, ["c"]];
matchables.indexOf(q);