How to Find the Index of an Object in an Array in JavaScript?

Estimated read time 1 min read

To find the index of an object in an array in JavaScript, you can use the findIndex method. The findIndex method returns the index of the first element in the array that satisfies the provided testing function.

Here’s an example:

const array = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Jim" },
];

const object = { id: 2, name: "Jane" };

const index = array.findIndex((item) => item.id === object.id && item.name === object.name);

console.log(index); // Output: 1

In this example, the findIndex method is used to find the index of the object { id: 2, name: "Jane" } in the array of objects. The findIndex method takes a testing function as an argument, which is used to compare each element in the array to the target object. In this case, the testing function compares the id and name properties of each element to the id and name properties of the target object. If a match is found, the findIndex method returns the index of the matching element, which is 1 in this example. If no match is found, the findIndex method returns -1.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply