-1
means the {name: "Banana"}
was not found in the array. That's because the first {name: "Banana"}
is a different object from the second {name: "Banana"}
.
If you were searching for a primitive type, it would work the way you are expecting. However, with an object, it looks to see that the actual objects are the same things (i.e., the same locations in memory) and not just that they have the same values.
So:
[0,1,2,3].indexOf(3); // 3, no surprise
var foo = {name: "Banana"};
[foo].indexOf(foo); // 0, no surprise
var bar = {name: "Banana"};
[foo].indexOf({name: "Banana"}); // -1, here's your wtf moment,
foo
is a different object than bar
. They just happen to have the same properties. But they occupy different locations in memory. Or, put another way, if I modify foo
, bar
remains unchanged.
Lots of libraries have solved the "deep equals" issue for you, so if you're using jQuery or Underscore or something, check there. Otherwise, look up how to implement because there are some gotchas.