How to Get Index of an Object in Array in JavaScript

Here are two ways to get an index of an object in an array in JavaScript:

  1. Using Array.findIndex()
  2. Using Array.map()

Method 1: Using an Array.findIndex()

Array.prototype.findIndex() method returns the index of the first element in the array that satisfies the provided testing function. No element passed the test if the findIndex() method returns -1.

Here is a code example:

const marks = [30, 100, 17, 23, 52, 20];

let index = marks.findIndex(marks => marks > 90);

console.log(index);

Output

1

Method 2: Using the Array.map() method

You can use the Array.map() method to get the index indirectly by transforming the array into an array of indices and then using Array.indexOf().

Here is a code example:

const marks = [30, 100, 17, 23, 52, 20];

const indices = marks.map((mark, idx) => (mark > 90 ? idx : -1));
const index = indices.indexOf(Math.max(...indices));

console.log(index);

Output

1

Here, we map the “marks” array to an array of indices based on the condition and then use Array.indexOf() to find the first non-negative index.