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 trialRoberto Hori
5,047 PointsMy solution to the challenge
I just used indexOf.
for (var i = 0; i < students.length; i += 1) {
student = students[i];
if(student.name.toUpperCase().indexOf(search.toUpperCase())>-1){
message += '<h2>Student: ' + student.name + '</h2>';
message += '<p>Track: ' + student.track + '</p>';
message += '<p>Points: ' + student.points + '</p>';
message += '<p>Achievements: ' + student.achievements + '</p>';
}
}
1 Answer
Iain Simmons
Treehouse Moderator 32,305 PointsYeah I did too, but Dave hasn't mentioned in the videos that indexOf
can be used on strings, in addition to arrays.
Here's my solution:
var html = '';
function print(nodeID, message) {
document.getElementById(nodeID).innerHTML = message;
}
function buildDefinitionList(obj) {
var prop;
var dListHTML = '<dl>';
for (prop in obj) {
dListHTML += '<dt>' + prop.charAt(0).toUpperCase() + prop.slice(1) + '</dt>';
dListHTML += '<dd>' + obj[prop] + '</dd>';
}
dListHTML += '</dl>';
return dListHTML;
}
function buildStudentList(list) {
var i;
var uListHTML = '<ul>';
for (i = 0; i < list.length; i++) {
uListHTML += '<li>' + buildDefinitionList(list[i]) + '</li>';
}
uListHTML += '</ul>';
return uListHTML;
}
function getMatchingStudents(list) {
var query;
var i;
var resultList;
// keep looping until the user quits
while(true) {
// reset the result list
resultList = [];
// prompt and convert to lowercase
query = prompt("Search student records: type a name [Iain] (or type 'quit' to end)");
// check if they want to quit
if (query === null || query.toLowerCase() === 'quit') {
break;
}
// loop through students and check if the name contains the search query
for (i = 0; i < list.length; i++) {
if (list[i].name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
// if so, push to the result list
resultList.push(list[i]);
}
}
// if there are results
if (resultList.length > 0) {
// build the list of matching students
html = buildStudentList(resultList);
} else {
// otherwise print a friendly not found message
html = '<p>Sorry, there are no students matching that name</p>';
}
// print html to output div
print('output', html);
}
}
getMatchingStudents(students);