Last updated on May 29, 2021 by Suraj Sharma
This tutorial is based on using the ES6 Array.findIndex()
method to get the first index of an item in an array of objects.
The findIndex()
method accepts a callback function as its argument, which iterates through all the elements in the array until the callbackFn
does not return a truthy value
Once the callbackFn
returns a truthy value, the findIndex()
method returns the index of the matched element; otherwise, it returns -1
.
The findIndex()
method is not supported in IE browsers but you can use a polyfill of Array.findIndex
In the below example, we will find the index of an object whose one of the keys contains a given value.
const array = [
{ id: 1, city: 'Mumbai'},
{ id: 2, city: 'New York'},
{ id: 3, city: 'Toronto'},
{ id: 4, city: 'London'}
];
const notMatchedIndex = array.findIndex((obj)=>obj.city === 'Berlin');
console.log(notMatchedIndex) // -1
const matchedIndex = array.findIndex((obj)=>obj.city === 'Toronto');
console.log(notMatchedIndex) // 2
Array.forEach() method can be used to find the index of an object
const array = [
{ id: 1, city: 'Mumbai'},
{ id: 2, city: 'New York'},
{ id: 3, city: 'Toronto'},
{ id: 4, city: 'London'}
];
function findIndex(array, value) {
let index = -1;
array.forEach((obj, i) => {
if (obj.city === value) {
index = i;
return;
}
})
return index;
}
console.log(findIndex(array, 'London'));
// 3
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.