0

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?

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

I'll add a quick function for checking shallow array equality
I use ii because it's easier to search against in code
non-literals? you probably mean non-primatives
3

Because

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

is false.

3 Comments

@What should I be doing to find ["a","b"] in matchables?
You will need to compare the elements piecewise; JavaScript does not have a way to test of two arrays have equivalent elements.
Everything they say is true, I added an example to mine to illustrate
-1

The way to get it to work would Be this:

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

2 Comments

Does not answer question
@This is not how I wish to solve this problem. I'm interested in finding by value, not reference.

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.