DEV Community

Cover image for How to get the index of an object from an array of objects in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the index of an object from an array of objects in JavaScript?

Originally posted here!

To get an index of an object from an array of objects, we can use the findIndex() array method on the array containing the object elements in JavaScript.

TL;DR

// Array of objects
const objsArr = [
  { name: "John Doe", age: 23 },
  { name: "Roy Daniel", age: 25 },
];

// Get the index of the object in the array
const indexOfObject = objsArr.findIndex((obj) => {
  // if the current object name key matches the string
  // return boolean value true
  if (obj.name === "Roy Daniel") {
    return true;
  }

  // else return boolean value false
  return false;
});

console.log(indexOfObject); // 1
Enter fullscreen mode Exit fullscreen mode

For example let's say we have an array of objects like this,

// Array of objects
const objsArr = [
  { name: "John Doe", age: 23 },
  { name: "Roy Daniel", age: 25 },
];
Enter fullscreen mode Exit fullscreen mode

Now, If we want to get the index of the object with the name key that matches Roy Daniel, we can use the findIndex() method.

  • the findIndex() requires a function as an argument.
  • the argument function will be passed the current array element every time an element is looped.
  • Inside this function, we can check if the name matches Roy Daniel and return the boolean value true if it matches and the boolean value false if not.
  • the findIndex() method returns the index of the object in the array.

It can be done like this,

// Array of objects
const objsArr = [
  { name: "John Doe", age: 23 },
  { name: "Roy Daniel", age: 25 },
];

// Get the index of the object in the array
const indexOfObject = objsArr.findIndex((obj) => {
  // if the current object name key matches the string
  // return boolean value true
  if (obj.name === "Roy Daniel") {
    return true;
  }

  // else return boolean value false
  return false;
});

console.log(indexOfObject); // 1
Enter fullscreen mode Exit fullscreen mode

That's all 😃!

See the above code live in JSBin

Feel free to share if you found this useful 😃.


Top comments (0)