Borislav Hadzhiev
Fri Oct 08 2021·2 min read
Photo by Aleksandr Ledogorov
To find the index of an object in an array, by a specific property:
findIndex
method on the array, passing it a function.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 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
.
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:
map()
method to iterate over the array, returning only the value of
the relevant property.indexOf()
method on the returned from map
array.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 = 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.
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.