how to find object index in an array in javascript

To find the index of a specific object in an array in JavaScript, you can use either the indexOf or findIndex method. Both methods search for an element in an array, and return the index of the first occurrence of the element. The difference is that indexOf works with primitive data types (like strings and numbers), while findIndex works with objects.

Here's an example of how to use the indexOf method to find the index of an object in an array:

index.tsx
const array = [{id: 1, name: 'John'}, {id: 2, name: 'Mary'}, {id: 3, name: 'Bob'}];
const obj = {id: 2, name: 'Mary'};
const index = array.indexOf(obj); // returns 1
166 chars
4 lines

And here's an example of how to use the findIndex method:

index.tsx
const array = [{id: 1, name: 'John'}, {id: 2, name: 'Mary'}, {id: 3, name: 'Bob'}];
const obj = {id: 2, name: 'Mary'};
const index = array.findIndex(element => element.id === obj.id); // returns 1
197 chars
4 lines

In both cases, the index variable contains the index of the object in the array variable. If the object is not found in the array, both methods return -1.

gistlibby LogSnag