/

How to Get the Index of an Item in a JavaScript Array

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
2
3
4
5
const letters = ['a', 'b', 'c'];

const index = letters.indexOf('b');

// The value of 'index' will be 1

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
2
3
4
5
6
7
8
9
10
11
12
13
const letters = [
{ letter: 'a' },
{ letter: 'b' },
{ letter: 'c' }
];

const index = letters.findIndex((element, index) => {
if (element.letter === 'b') {
return true;
}
});

// The value of 'index' will be 1

By using the findIndex method, you can search for a specific object and retrieve its index within the array.

Tags: JavaScript, array, indexOf, findIndex