"Build a Basic PHP Website (2018)" was retired on December 10, 2019. You are now viewing the recommended replacement.

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 Solution

sasipim Suksareewattanakul
sasipim Suksareewattanakul
5,417 Points

Can't display multiple students with the same name. Still only show the last student with the same name only.

I used .push() to add a new object of students to a new array. I checked my new arrays and saw that the numbers of objects in there are correct based on the number of students with the same name. but when i print it out, still only print out only one record which is the last student. please help check my code!!

var message = "";
var student;
var search;
var groupStudents = [];

function print(message) {
  var outputDiv = document.getElementById("output");
  outputDiv.innerHTML = message;
}

function getStudentReport (student) {
    var report = "<h2>Student: " + student.name + "</h2>";
    report += "<p>Track: " + student.track + "</p>";
    report += "<p>Achievement: " + student.achievement + "</p>";
    report += "<p>Points: " + student.points + "</p>"; 
    return report; 
  }

while (true) {
  search = prompt("Type in the name of the student to search. Type 'quit' if you'd like to quit");
  if (search === null || search.toLowerCase() === "quit") {
    break;      
  } 
  for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (search.toLowerCase() === student.name) {
      groupStudents.push(student); 
    } 
  } 

  if (groupStudents.length>0) {
  for (var i = 0; i < groupStudents.length; i += 1) {
    message = getStudentReport(groupStudents[i]);
    print(message);
  }
} else {
  alert("This student name " + search + " is not in our record."); 
}

}

2 Answers

Tsenko Aleksiev
Tsenko Aleksiev
3,819 Points

Hmm... I don't see where you define the students array? I mean you use it here "for (var i = 0; i < students.length; i += 1)" ( students.length ), but I don't see it defined anywhere...

sasipim Suksareewattanakul
sasipim Suksareewattanakul
5,417 Points

Hi, thank you for your response. the students variable was declared in a separate js file.

Tsenko Aleksiev
Tsenko Aleksiev
3,819 Points

No problem, Iā€™m glad I helped :)