What\'s the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: \'world\',
foo: \'ba
var idx = myArray.reduce( function( cur, val, index ){
if( val.hello === "stevie" && cur === -1 ) {
return index;
}
return cur;
}, -1 );
This works without custom code
var arr, a, found;
arr = [{x: 1, y: 2}];
a = {x: 1, y: 2};
found = JSON.stringify(arr).indexOf(JSON.stringify(a)) > - 1;
// found === true
Note: this does not give the actual index, it only tells if your object exists in the current data structure
I did some performance testing of various answers here, which anyone can run them self:
https://jsperf.com/find-index-of-object-in-array-by-contents
Based on my initial tests in Chrome, the following method (using a for loop set up inside a prototype) is the fastest:
Array.prototype.indexOfObject = function (property, value) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i][property] === value) return i;
}
return -1;
}
myArray.indexOfObject("hello", "stevie");
This code is a slightly modified version of Nathan Zaetta's answer.
In the performance benchmarks I tried it with both the target being in the middle (index 500) and very end (index 999) of a 1000 object array, and even if I put the target in as the very last item in the array (meaning that it it has to loop through every single item in the array before it's found) it still ends up the fastest.
This solution also has the benefit of being one of the most terse for repeatedly executing, since only the last line needs to be repeated:
myArray.indexOfObject("hello", "stevie");