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
?
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 )
Why not simply make a loop ?
function indexOfId(array, id) {
for (var i=0; i<array.length; i++) {
if (array[i].id==id) return i;
}
return -1;
}
The fact that there are many facilities in js (or js libraries) doesn't mean you must not, sometimes, write a loop. That's fast and simple.
ES6 Array.findIndex
const myArray = [{id:1}, {id:2}, {id3}];
const foundIndex = myArray.findIndex((el) => (el.id === 3));