Home >Web Front-end >JS Tutorial >How to Efficiently Find the Index of an Object Matching a Specific Condition in a JavaScript Array?
Finding the Index of an Object Meeting Conditions in an Array
Question:
How can an index within an array of objects meeting a specific condition be efficiently and directly identified?
Consider an array of objects:
var hello = { hello: 'world', foo: 'bar'}; var qaz = { hello: 'stevie', foo: 'baz'} var myArray = []; myArray.push(hello, qaz);
Task:
Determine the index of the element whose "hello" property is equal to 'stevie' in the "myArray" array. In this example, the result should be 1.
Answer:
An elegant solution can be achieved using the "map" function:
const pos = myArray.map(e => e.hello).indexOf('stevie');
This code line accomplishes the following steps:
Consequently, the variable "pos" will hold the desired index, which is 1 in the provided example.
The above is the detailed content of How to Efficiently Find the Index of an Object Matching a Specific Condition in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!