How to get the index or position of a specific element in an array in JavaScript?

November 16, 2020 - 2 min read

To get the index or position of a specific element in an array, you can use the indexOf() array method in JavaScript.

Consider this array of numbers,

// numbers array
const numsArr = [23, 456, 65, 34];

Let's get the index or position of number 65 in the array. It can be done using the indexOf() method and passing 65 as an argument to the method like this,

// numbers array
const numsArr = [23, 456, 65, 34];

// get the position or index
// of 65 in the array
// by passing 65 as an
// argument to the method
const index = numsArr.indexOf(65);

console.log(index); // 2
  • The method returns the index number of the element if it is found and returns -1 if it is not found.

See this example live in JSBin.

You can also tell the method of the position you want to start searching in the array by passing the index as the second argument to the method.

Suppose I want to start searching in the array from index 1. I can define it like this,

// numbers array
const numsArr = [23, 456, 65, 34];

// get the position or index
// of 65 in the array
// by passing 65 as an
// argument to the method
// but start searching from index 1
const index = numsArr.indexOf(65, 1);

console.log(index); // 2

Feel free to share if you found this useful 😃.