What\'s the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: \'world\',
foo: \'ba
Array.prototype.findIndex is supported in all browsers other than IE (non-edge). But the polyfill provided is nice.
var indexOfStevie = myArray.findIndex(i => i.hello === "stevie");
The solution with map is okay. But you are iterating over the entire array every search. That is only the worst case for findIndex which stops iterating once a match is found.
var searchTerm = "stevie",
index = -1;
for(var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i].hello === searchTerm) {
index = i;
break;
}
}
or as a function:
function arrayObjectIndexOf(myArray, searchTerm, property) {
for(var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
}
arrayObjectIndexOf(arr, "stevie", "hello"); // 1
Just some notes:
For example,
var a = {obj: 0};
var b = [a];
b.indexOf({obj: 0}); // -1 not found