How to find index of an item in JavaScript Object Array?

Recently while working I came across a scenario. I had to find index of a particular item on given condition from a JavaScript object array. In this post we will see how to find index of object from JavaScript array of object.

Let us assume we have a JavaScript array as following,


var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.


function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

for (var i = 0; i < arraytosearch.length; i++) {

if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}

You can use the function to find index of a particular element as below,


var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.

10 responses to “How to find index of an item in JavaScript Object Array?”

  1. Thanks DJ. For such a great example..
    You made learning JS so easy..

  2. […] How to find index of an item in JavaScript Object Array? (Dhananjay Kumar) […]

  3. Thanks for the solution! But what if one of the name were repeated?

  4. Thanks for the solution… this is really useful….

  5. i have a diff scenario i have an array of objects and have to search through it to get the id == the id in another object and do something on it , how do i do it

  6. I think there might be performance issue when data gets large it will be O(n) which is not ideal for a search it should be O(log(n))
    I wish there is a way to search with built in function.

  7. There is a way to search with a built in function, for example with Array.prototype.filter
    The question is if you have to support IE<9 and other older browsers

    more info at: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

  8. But the sample is never going further than arraytosearch[0] because of the premature return call!
    I’d rather collect the results in a new array and return that if it’s greater than zero.

  9. This is epic!! thanks you so much for this- almost 4 years later =)

  10. Very useful, thank you.

Leave a comment

Create a website or blog at WordPress.com