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
?
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.
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.
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.
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.
Or with ES6 syntax:
let index = myArray.map( el => el.id ).indexOf(4)
or
let index = myArray.findIndex( el => el.id === 4 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With