5/6 Add the option if the surname not exist?


#1

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}

var search = function (lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if(lastName === contacts[i].lastName) {
printPerson(contacts[i]);
}else{
console.log("That surname could not be found")
}
};
};
search("Mones");

I want to add the option if the surname not exist in the contacts i add else, but the problem is that appears bobby jones And That surname could not be found is search for Jones? And if i search for Mones prints two times That surname could not be found?


#2

That is because when it look for a name that does not exist, it does not get out of the for loop, it continues.
For example when you look for "jones" the for loop first finds bob, let's you know that "That surname could not be found" and then the for loop finds mary and says again that "That surname could not be found"

Jump out of the for loop after it logs to the console that the name cannot be found.


#3

Then a solution could be then a while loop?


#4

I have something different in my mind. I don't think this is the greatest way to do it, but its simple :relaxed:

var search = function (lastName) {
    var contactsLength = contacts.length;
    var exists = false;
        for (var i = 0; i < contactsLength; i++) {
            if(lastName === contacts[i].lastName) {
                printPerson(contacts[i]);
                exists = true
            } 
        }
        if(!exists){
            console.log("That name dos not exists");
        }

#5

Yes also I thought this option
Honestly I can not think of another option!
I'm still a novice in these wanderings! :astonished: Thank you for your attention


#6

Great, just had to twig a little of your code and it worked like charm: code is bellow for those who might struggle in future:

var search = function (lastName) {
var contactsLength = contacts;
for (var i = 0; i < contactsLength.length; i++) {
if(lastName === contacts[i].lastName) {
printPerson(contacts[i]);

        } 
    }

    } 
    search('Jones');