Reputation: 75
I have an array of objects. I am attempting to locate the index of an object inside this array, however it always returns -1 unless I "cheat". I cannot see the difference here and it console.logs the exact same output both ways. It only works one way... Is this a bug?
var arr = [{ un: 'test', uid: 1 }];
console.log("array",arr,typeof arr);
var obj = { un: 'test', uid: 1};
console.log("obj",obj);
console.log(arr[0],typeof arr[0]);
console.log("indexOf",arr.indexOf(obj));
arr.push(obj);
console.log(arr);
console.log("indexOf",arr.indexOf(obj));
The Output is this:
array [ { un: 'test', uid: 1 } ] object
obj { un: 'test', uid: 1 }
{ un: 'test', uid: 1 } 'object'
indexOf -1
[ { un: 'test', uid: 1 }, { un: 'test', uid: 1 } ]
indexOf 1
For the life of me, I cannot see the difference here. Am I missing something simple here? It's possible... considering the hours of coding, simple things get overlooked.
Upvotes: 0
Views: 611
Reputation: 3080
In javascript, Objects are always references to the object itself (pointers to memory address where the object is stored), so doing
var arr = [{ un: 'test', uid: 1 }];
var obj = { un: 'test', uid: 1};
console.log("obj",obj);
will never return anything else than -1 because obj has a different address than the object in arr. That's why, if you push obj
in arr
it does work.
So Array.prototype.indexOf
with an object as an argument will look for the same reference, whereas Array.prototype.indexOf
with number, string, null will look for the value.
If you want to find the index of an object with specific properties use :
var arr = [{ un: 'test', uid: 1 }];
var index = arr.findIndex(i => i.un === 'test' && i.uid === 1);
Here is the doc for findIndex : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Upvotes: 1