Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge

Why wont the array.IndexOf() method work for this

I have most of want working in this, I am using a combination of a for loop to go through and retrieve information from the array, and a while loop for the search. The prompt works as expected if user inputs quit or list, however prompt does not work as expected if user searches for a that exists in the array, I have tried an array.IndexOf() method to retrieve the information and print out to page. Is there a way to get Array.indexOf() method like in the grocery shopping list search. to work properly in this context.The array I am trying to retrieve info from is a array of objects. here is a snapshot https://w.trhou.se/6je9mimoji

3 Answers

Sakib Rahman
Sakib Rahman
2,154 Points

Try using your own index function. Here is a example of mine:

function getIndex(arrayName, search, value) {
    for(var i = 0; i < arrayName.length; i++) {
        if (arrayName[i][value].toLowerCase() === search) return i;
    }
    return -1;
}

To call it you would first put in the name of the array (in this case its students), then you would put your 'search' variabl le, and finally you would put in the property you are trying to match against (in this case name).

getIndex(students, search, "name");

You can check at the MDN documentation about how to use the function and remember almost all the function names start with lowercase "array.indexOf();"

students is an array of objects. The indexOf method searches for the specified item. In this case, the item to look for should be an object. Your code is searching for a string.

Not sure if this is the most efficient solution but I would iterate over each students object and check if the name matches the input from the user.

Hope this helps.

Ivana Lescesen
Ivana Lescesen
19,442 Points

Hi Frederic, would you be able to show me how to write the code above so that the The indexOf method is functioning corectly. Thank you so much :)