"5. Finding that Special Someone" need assist with for loop


#1

my code work correctly, but I have a question.
How can I explain the code that no need to do for loop again, if we found our lastName?
I want to return only one result. Not two (for each element of array).
Here is my code, if you have interest.


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

thank you in advance!
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 search(lastName){
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++){
if ( contacts[i].lastName === lastName ){
printPerson(contacts[i]);
}
else {
return "Error, sry";
};
}
}

search("Jones");


thank you in advance!


#2

@scriptpro63538,

You could remove

else {
 return "Error, sry";
 };

and do not use a semi-colon-; IN or at the END of your IF ELSE statement.
http://stackoverflow.com/questions/17036135/why-is-it-that-semicolons-are-not-used-after-if-else-statements


#3

Thx about ";".

Still, if we wont to print "Error" when we don't find conformity we need that else(

General question is "How to return only one result."


#4

contacts[i].lastName === lastName

I had the same problem.


#5

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]);
}
}

/*Create a search function
then call it passing "Jones"*/

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

};
search("Jones");