Home > Web Front-end > JS Tutorial > How to Find the Index of an Object in a JavaScript Array?

How to Find the Index of an Object in a JavaScript Array?

Mary-Kate Olsen
Release: 2024-12-01 05:18:10
Original
869 people have browsed it

How to Find the Index of an Object in a JavaScript Array?

Finding an Object's Index in an Array

When searching an array of objects for a specific element, the indexOf method is not applicable. This article presents a direct approach to retrieve the index of an object meeting a certain condition.

Consider an array of objects like this:

var hello = { hello: 'world', foo: 'bar'};
var qaz = { hello: 'stevie', foo: 'baz'}

var myArray = [];
myArray.push(hello, qaz);
Copy after login

To find the index of the element whose hello property equals 'stevie', we can utilize the map function:

const pos = myArray.map(e => e.hello).indexOf('stevie');
Copy after login

The map function iterates through the array, extracting the value of the hello property for each object and creating a new array. The indexOf method can then be applied to this new array to find the index of the element with the desired value ('stevie' in this case).

This approach provides a single-line solution for finding the index of an object matching a specific condition within an array of objects.

The above is the detailed content of How to Find the Index of an Object in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template