How to Find the Array Index with a Value in JavaScript [3 Ways]

Here are the three ways to find an array index with a value in JavaScript:

  1. Using indexOf()
  2. Using findIndex()
  3. Using forEach()

Method 1: Using findIndex()

The array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

const avengers = ["Thor", "Iron man", "loki", "hulk", "wanda", "dr strange"];

console.log("Index of loki: ", avengers.indexOf("loki"));
console.log("Index of hulk: ", avengers.indexOf("hulk"));
console.log("Index of Thor: ", avengers.indexOf("Thor"));
console.log("wrong value index: ", avengers.indexOf("captain"));

Output

Index of loki: 2
Index of hulk: 3
Index of Thor: 0
wrong value index: -1

Method 2: Using the array indexOf() function

JavaScript findIndex() method is used to execute a function for each array element. It returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

const values = [34, 12, 89, 49, 21, 43, 1];
// Arrow function
console.log(values.findIndex((element) => element > 40));

values.findIndex((element, index) => {
  if (element > 40) {
   console.log(`index of ${element} is ${index}`)
  }
});

Output

2
index of 89 is 2
index of 49 is 3
index of 43 is 5

Method 3: Using the forEach() function

We get an index of an element by using a custom function with the forEach() function to iterate that array and find the index of that passed element.

const avengers = ["Thor", "Iron man", "loki", "hulk", "wanda", "dr strange"];

function getElementIndex(value, array) {
   let index = -1;
   array.forEach((item, i) => {
     if (item === value) {
        index = i;
   }
 });
 return index;
}

console.log("index of loki is : ", getElementIndex("loki", avengers));

Output

index of loki is : 2