Get the index of an Object in an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.
  2. Check if the each object has a property with a specific value.
  3. The findIndex method will return the index of the first matching object.
index.js
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const index = arr.findIndex(object => { return object.id === '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.

On each invocation of the callback function, we check if the object's property is equal to a specific value and return either true or false.

If the 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, 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.
index.js
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const index = arr.map(object => object.id).indexOf('c'); console.log(index); // 👉️ 2

We use the Array.map method to get an array of the relevant values.

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

Then we call the Array.indexOf method on the array to get the index of the specific 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 array of objects.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.