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.tsx166 chars4 lines
And here's an example of how to use the findIndex
method:
index.tsx197 chars4 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