Baz
Baz

Reputation: 13125

Find an Array in a two dimensional Array

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?

Upvotes: 0

Views: 69

Answers (3)

Andrew Templeton
Andrew Templeton

Reputation: 1696

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

Upvotes: 7

QBM5
QBM5

Reputation: 2788

The way to get it to work would Be this:

var q = ["a", "b"];
var matchables = [q, ["c"]];
matchables.indexOf(q);

Upvotes: -1

Matt Ball
Matt Ball

Reputation: 359776

Because

["a","b"] === ["a","b"]

is false.

Upvotes: 3

Related Questions