How can I get the index of an element in an array in JavaScript?
Ava W
ava w profile pic

To get the index of an element in an array in JavaScript, you can use various methods provided by the Array API. Here's a step-by-step guide on how to achieve this: 1. Create an array with the elements you want to work with:

1
2
3

   const array = ['apple', 'banana', 'orange', 'pear'];
   

2. Use theindexOf() method: TheindexOf() method returns the first index at which a given element is found in the array. If the element is not found, it returns -1.

1
2
3
4
5

   const element = 'banana';
   const index = array.indexOf(element);
   console.log(index);  // Output: 1
   

3. Use thefindIndex() method: ThefindIndex() method returns the index of the first element in the array that satisfies the provided testing function. If no element is found, it returns -1.

1
2
3
4

   const index = array.findIndex((element) => element === 'banana');
   console.log(index);  // Output: 1
   

4. Use thefind() method in combination withindexOf() orfindIndex(): Thefind() method returns the first element in the array that satisfies the provided testing function. You can then useindexOf() orfindIndex() on the array to get the index of that element.

1
2
3
4
5

   const element = array.find((element) => element === 'banana');
   const index = array.indexOf(element);
   console.log(index);  // Output: 1
   

or

1
2
3
4

   const index = array.findIndex((element) => element === array.find((element) => element === 'banana'));
   console.log(index);  // Output: 1
   

5. Use afor loop to iterate over the array and find the index: If you need more control or flexibility, you can use afor loop to manually iterate over the array and check each element until you find a match.

1
2
3
4
5
6
7
8
9
10
11
12
13

   const element = 'banana';
   let index = -1;

   for (let i = 0; i < array.length; i++) {
     if (array[i] === element) {
       index = i;
       break;
     }
   }

   console.log(index);  // Output: 1
   

Choose the method that best fits your requirements and the specific context in which you need to find the index of an element in the array.