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

How to Efficiently Find the Index of an Object Matching a Specific Condition in a JavaScript Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 18:03:151003browse

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:

  • Maps each element in "myArray" to its "hello" property, effectively creating an array of "hello" values.
  • Uses the "indexOf" function to search for the index of the desired value, in this case 'stevie', within the intermediate array generated by the mapping.

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!

Statement:
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