2
var myWidth = 20;
var myHeight = 30;

allDims = [
  {w: 20, h: 30},
  {w: 10, h: 15}
]

if ($.inArray({w: myWidth, h: myHeight}, allDims) !== -1) {
   ...
}

Why is the if-condition always returning -1?

1
  • 4
    It's always -1 because one object is never equal to another object, even if they contain the same data. The only exception to that rule is when the object stored in the array is stored by reference, and the object you're testing with is also a reference to that same object. In that case, they literally are the same object. Commented Jun 24, 2013 at 14:15

1 Answer 1

4

This doesn't work because the equality test on objects is based on the equality of references.

From the MDN :

Two distinct objects are never equal for either strictly or abstract comparisons

So you must implement the index search yourself, by looping and comparing both w and h.

For example :

   var index = -1;
   for (var i=0; i<allDims.length; i++) {
      if (allDims[i].w==myWidth && allDims[i].h==myHeight) {
          index = i;
          break;
      }
   }

If you want something more elegant, you could use filter and pass a function, but it would iterate over the whole array even when not needed. A generic function similar to indexOf but taking a callback to check equality can be designed :

Array.prototype.indexFunc = function(o, equal) {
  for (var i=0; i<this.length; i++) {
     if (equal(o,this[i])) return i;
  }
  return -1;
}
console.log(allDims.indexFunc({w:10, h:15}, function(a,b) {
       return a.w==b.w && a.h==b.h
})); // logs 1
Sign up to request clarification or add additional context in comments.

1 Comment

this answer does not deserve downvotes, it is 100% correct. The other (current) answer does not deserve upvotes - it is 100% incorrect.

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.