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 = {

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


Or with ES6 syntax:

let index = el => ).indexOf(4)


let index = myArray.findIndex( el => === 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.


If each id is unique, you can do it like this:

o1 = {id:1}
o2 = {id:2}
o3 = {id:3}
o4 = {id:4}
a = [o1,o2,o3,o4]
a.indexOf( a.filter( function(i){return} )[0] );

ES6 Array.findIndex

const myArray = [{id:1}, {id:2}, {id3}];
const foundIndex = myArray.findIndex((el) => ( === 3));

You could also try a recursive function, though @xdazz's looks rather attractive.

var indexOfId = function(arr, id, index) {
    if (!index) { index = 0; }
    if (arr[index].id == id) {
      return index;
    return ((index += 1) >= arr.length) ? -1 : indexOfId(arr, id, index);

You can use .reduce(), which lets you reduce an Array down to a single value.

var obj_idx = myArray.reduce(function(idx, item, i) {
  return === 4 ? i : idx;
}, -1);

The -1 is a default value if no match is found.

If you have multiple uses for this, you may want to make a function factory.

function idxForID(target) {
    return function(idx, item, i) {
      return === target ? i : idx;

And then use it like this.

var obj_idx = myArray.reduce(idxForID(4), -1);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.