Get the index of an Object in an Array in JavaScript

avatar

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.
index.js
// Not supported in IE 6-11 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.

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.
index.js
// Supported in IE 9-11 const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}]; const index = arr.map(object => object.id).indexOf('c'); console.log(index); // ๐Ÿ‘‰๏ธ 2

In the code snippet 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 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee