Daniel Fernandez Daniel Fernandez - 3 months ago 5
Javascript Question

Index of javascript object in array of objects

I have an array of objects in javascript, something like

var arrayobj = [{a:'a'},{b:'b'},{c:'c'}]
(but with more complex values).

Now I check the index of some object manually, like

And I got
Object {b: "b"}

Now I type

and the response is
(aka not found).

Anyone could tell me why this happens? I have read the documentation on indexOf method and arrays, but I still have no clue.

Thanks in advance!


indexOf checks for equality (specifically strict equality, ===, but it doesn't matter for this question). Two different objects are not equal to each other even if they have the same properties. The object in your array and the one you pass to indexOf are different objects, and so they don't match.

If you searched for the same object, it would find it:

var b = {b:'b'};
var arrayobj = [{a:'a'},b,{c:'c'}];
console.log(arrayobj.indexOf(b)); // 1