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.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

10 thoughts on “How to find index of an item in JavaScript Object Array?

  1. 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

  2. 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.

  3. 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.

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading