How to Get the Index of an Item in a JavaScript Array
In JavaScript, there are different ways to retrieve the index of an item in an array based on its value. In this blog, we will explore two methods for accomplishing this task.
Method 1: Using indexOf for Primitive Values
If the item you’re searching for is a primitive value (e.g., string or number), you can utilize the indexOf
method of an array. Here’s an example:
1 | const letters = ['a', 'b', 'c']; |
Note: The index of an array starts from 0.
Method 2: Using findIndex for Objects
However, if the item you’re searching for is an object, the indexOf
method won’t work because objects are compared by reference, not by their values. To find the index of an object in an array, you can employ the findIndex
method. This method takes a function that is executed for each item in the array, passing the element and its index as arguments. Here’s an example:
1 | const letters = [ |
By using the findIndex
method, you can search for a specific object and retrieve its index within the array.
Tags: JavaScript, array, indexOf, findIndex