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?

Answers:

Answer
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.

Answer

Or with ES6 syntax:

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

or

let index = myArray.findIndex( el => el.id === 4 )
Answer

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.

Answer

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 i.id==4} )[0] );
Answer

ES6 Array.findIndex

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

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);
};
Answer

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 item.id === 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 item.id === target ? i : idx;
    };
}

And then use it like this.

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.