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

A better way to solve 2 users with the same name and when there is no user?

So I have solved the challenge but I was wondering if using the 'studentFound' flag is necessary. I have the feeling this might be a bit cleaner. Any suggestions?

<div id="text">ble</div>
var html = "";
var search = "";
var students = [{
    name: "Karl",
    track: "Java",
    achievements: 50,
    points: 4543
}, {
    name: "Magnus",
    track: "Javascript Advance",
    achievements: 12,
    points: 1200
}, {
    name: "Ingvi",
    track: "Front end",
    achievements: 30,
    points: 3999
}, {
    name: "Leopold",
    track: "Angularjs",
    achievements: 2,
    points: 34
}, {
    name: "Ingvi",
    track: "HTML & CSS for beginners",
    achievements: 1,
    points: 12
}];

function print(el, message) {
    document.getElementById(el).innerHTML = message;
}

function getStudentReport(stud) {
    var report = '<h4>Student: ' + stud.name + '</h4>';
    report += '<p>Track: ' + stud.track + '</p>';
    report += '<p>Points: ' + stud.points + '</p>';
    report += '<p>Achievements: ' + stud.achievements + '</p>';
    return report;
}

while (true) {

    search = prompt('Search for a student name (ex.Ingvi) or type quit');

    if (prompt === null || search.toLowerCase() === "quit") {
        break;
    }

  // 1. Create a flag
    var studentFound = false;

    for (var i = 0; i < students.length; i++) {
        var stud = students[i];

        if (search == stud.name) {
            html += getStudentReport(stud);
            print('text', html);
            // 2a. set flag to true when there is a match
            studentFound = true;
        }

        // 2b. or when flag stays false print some text out.
        if (!studentFound) {
            print('text', "Sorry <b>" + search + "</b> not found");
        }
    }

    html = "";
}

a fiddle

1 Answer

The flag is not necessary and you can simply remove the variable and the second if condition and make that an else to your initial if student found condition.

jsFiddle

Hi Chyno, I actually did that at the beginning but it did not work. Because I am looping through all students names and adding everyone to the html variable in case of multiple instances.