find index of an object in an array in javascript

To find the index of an object in an array in JavaScript, you can use the indexOf() method. However, since the array contains objects and not primitive values, you need to compare the objects by reference in JavaScript.

Here's an example:

index.tsx
const myArray = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}];

const obj = {name: 'Bob'};
const index = myArray.indexOf(obj);

console.log(index); // 1
159 chars
7 lines

In this example, we have an array of objects. We want to find the index of the object that has the name "Bob". We create a new object with the same name "Bob" and use the indexOf() method to find the index of the first occurrence of this object in the array.

Note that if the object is not found in the array, the indexOf() method returns -1.

gistlibby LogSnag