How to Get the Index of an Array that Contains Objects in JavaScript

There are several methods in JavaScript that can help you access the index of the object from the array of an object. Let’s have a look at each method and find the most appropriate one for your case.

map()

The map() method creates a separate array and calls a function for every array element. This method invokes the defined function once for every element in the array, maintaining the order:

let array = [{
  prop1: 'value1',
}, {
  prop2: 'value2',
}, {
  prop3: 'value3',
}];
function arrayMap() {
  let pos = array.map(function (e) {
    return e.prop2;
  }).indexOf('value2');
  console.log("Index of 'value2'  is = " + pos);
}
arrayMap();

for loop

Another fast method is the for loop setted up inside a prototype:

let array = [{
  prop1: 'value1',
}, {
  prop2: 'value2',
}, {
  prop3: 'value3',
}];
Array.prototype.indexOfObject = function (property, value) {
  for (let i = 0, len = this.length; i < len; i++) {
    if (this[i][property] === value) return i;
  }
  return -1;
}
console.log(array.indexOfObject("prop2", "value2"));

findIndex()

You can also use a native and convenient function findIndex() as follows:

let myArray= [
 {
   name: 'Jack',
   age: 25,
 },
 {
   name: 'Maria',
   age: 22,
 }];
let index = myArray.findIndex( element => {
  if (element.name === 'Maria') {
    return true;
  }
});
console.log('Maria is at index: ' + index);

The Array.prototype.findIndex() method returns an index in the array if an element in the array satisfies the provided testing function; otherwise, it will return -1, which indicates that no element passed the test. It executes the callback function once for every index in the array until it finds the one where callback returns true.

Do you find this helpful?

Related articles