What's the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = { hello: 'world', foo: 'bar' }; var qaz = { hello: 'stevie', foo: 'baz' } var myArray = []; myArray.push(hello,qaz);
Now I would like to have the indexOf
the object which hello
property is 'stevie'
which, in this example, would be 1
.
I'm pretty newbie with JavaScript and I don't know if there is a simple method or if I should build my own function to do that.
The indexOf method returns the index of the first occurrence of a value in an array.
There is no direct indexOf function in java arrays.
The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.
I think you can solve it in one line using the map function:
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With