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");
hello
andqaz
? – Playhousevar elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor); var objectFound = array[elementPos];
[link] (https://mcmap.net/q/64584/-in-an-array-of-objects-fastest-way-to-find-the-index-of-an-object-whose-attributes-match-a-search) – Wamsley