Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, I’m going to show you how I find the index of an object in an array, here I will use the javascript findIndex() method and some conditions to find the exact object in the array.

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

Well, let’s start today’s topic How to find the index of an object in an array in javascript?

Before going to code we have below things.

First, we have any object property value which we will use to find objects in an array.

The second is an array of objects 😆.

Okay, let’s plan what we are going to do in code.

  1. Create a sample array of objects variable.
  2. To get index, use findIndex() method
  3. write condition to get the index of desired object
// Create sample array of objects variable.
const domains = [
  {id: 1, name: "infinitbility", domain: "infinitbility.com"},
  {id: 2, name: "aGuideHub", domain: "aguidehub.com"},
  {id: 1, name: "SortoutCode", domain: "sortoutcode.com"},
];

// To get index, use `findIndex()` method
// write condition to get index of desire object
let index = domains.findIndex(e => e.id == 2);

console.log("index", index);
// Expected 'index' 1

In the above example, I’m using the object id property to get desired object index from the array, you can use any property which unique.

Here, as per expectation it should show the index is 1, let’s check the output.

javascript, find the index of an object in an array example
javascript, find the index of an object in an array example

I hope it’s help you, All the best 👍.