Get the index of an Object in an Array in JavaScript


Borislav Hadzhiev

Fri Oct 08 20212 min read

Get the index of an Object in an Array #

To find the index of an object in an array, by a specific property:

  1. Call the findIndex method on the array, passing it a function.
  2. The function should return an equality check on the relevant property.
  3. The findIndex method returns the index of the first element in the array, for which the callback function returns a truthy value.
// Not supported in IE 6-11 const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const index = arr.findIndex(object => { return === 'b'; }); console.log(index); // 👉️ 1

The function we passed to the Array.findIndex method gets called with each element in the array until it returns a truthy value or iterates over all elements in the array.

In the example, we check if the object's property is equal to a specific value and return either true or false.

If the callback function we pass to the findIndex method never returns a truthy value, the method returns -1.

The findIndex method is not supported in Internet Explorer. If you need to support the browser, add a polyfill for the method, use babel to compile your code to an older version of JavaScript, or use the next approach covered in this article.

To find the index of an object in an array, by a specific property:

  1. Use the map() method to iterate over the array, returning only the value of the relevant property.
  2. Call the indexOf() method on the returned from map array.
  3. The indexOf method returns the index of the first occurrence of a value in an array.
// Supported in IE 9-11 const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const index = =>'c'); console.log(index); // 👉️ 2

In the code snippet we use the method to get an array of the relevant values.

const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const values = => console.log(values) // 👉️ ['a', 'b', 'c']

Then we call the Array.indexOf method on the array to get the index of the value.

Since the map method iterates over all of the array's elements, the ordering of the elements is preserved and is the same for both the array of values and the objects array.

If the indexOf method doesn't find an element with the passed in value it returns -1, just like the findIndex method.

This solution is definitely not as elegant and direct as the findIndex one, however it gets the job done if you have to support Internet Explorer.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.