What\'s the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: \'world\',
foo: \'ba
You can use a native and convenient function Array.prototype.findIndex()
basically:
The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.
Just a note it is not supported on Internet Explorer, Opera and Safari, but you can use a Polyfill provided in the link below.
More information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello, qaz);
var index = myArray.findIndex(function(element, index, array) {
if (element.hello === 'stevie') {
return true;
}
});
alert('stevie is at index: ' + index);