In this article, you’ll learn how to get the index of an object in a javascript array. There are various ways to find the index of an object in a javascript array such as: the findIndex()
method, map()
method, and Array.forEach()
method.
Here are some examples to get the index of an object in a Javascript array
In this example, We used 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 condition is not to pass a test. This method returns -1 if no match is found, otherwise, it returns an element index.
Note: The findIndex()
method is not supported in IE(6-11) browsers but you can use a polyfill of Array.findIndex.
const array = [
{ name: "Tom", city: "Mumbai" },
{ name: "Harry", city: "New York" },
{ name: "Lucy", city: "Toronto" },
{ name: "Monica", city: "London" },
];
console.log(array.findIndex((obj) => obj.city === "Berlin"));
//When no match found it returns -1
// output ==> -1
console.log(array.findIndex((obj) => obj.city === "Toronto"));
//when match is found it returns element index
// output ==> 2
In this example, we used the map()
method to get the index of an object in a javascript array. The map()
method creates a new array and calls a function for each element in an array. This method returns -1 if no match is found, otherwise, it returns an element index.
const array = [
{ name: "Tom", city: "Mumbai" },
{ name: "Harry", city: "New York" },
{ name: "Lucy", city: "Toronto" },
{ name: "Monica", city: "London" },
];
console.log(array.map((i) => i.city).indexOf("Berlin"));
//When no match found it returns -1
// output ==> -1
console.log(array.map((i) => i.city).indexOf("Toronto"));
//when match is found it returns element index
// output ==> 2
In this example, we used the Array.forEach()
method to get the index of an object in the javascript array.
const array = [
{ name: "Tom", city: "Mumbai" },
{ name: "Harry", city: "New York" },
{ name: "Lucy", city: "Toronto" },
{ name: "Monica", 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,'Berlin'));
//When no match found it returns -1
// output ==> -1
console.log(findIndex(array,'London'));
//when match is found it returns element index
// output ==> 3
I hope this article will help you to understand how to get the index of an object in a javascript array.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments