Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of an array's element based on its properties

I have a JavaScript array of objects like this:

var myArray = [{...}, {...}, {...}]; 

Each object has unique id among other properties:

{    id: 4,   property1: 'something',   property2: 'something' } 

How can I get an index of a particular object in that array, if I only know its id property? So if I know that myArray[x].id == 4, how can I find x?

like image 517
Robert Kirsz Avatar asked Sep 23 '12 14:09

Robert Kirsz


People also ask

How do you find the index of an element in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you get the index of an element in a list in JS?

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.

How do you find the index of an element in array TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


2 Answers

var index = myArray.map(function(el) {   return el.id; }).indexOf(4); 

For IE below version 9, map need a patch, or just use a loop.

like image 143
xdazz Avatar answered Oct 20 '22 09:10

xdazz


Or with ES6 syntax:

let index = myArray.map( el => el.id ).indexOf(4) 

or

let index = myArray.findIndex( el => el.id === 4 ) 
like image 43
Dmitry Shvedov Avatar answered Oct 20 '22 07:10

Dmitry Shvedov