Basic JavaScript: Profile Lookup-Somequestion

Basic JavaScript: Profile Lookup-Somequestion
0.0 0

#1

Tell us what’s happening:

It can’t pass.But in the way followed it can ,I don’t know why.

Your code so far




function lookUpProfile(name, prop){


  var namecheck=0;
 //  for(var i=0; i<=contacts.length-1; i++) {
 //       if (contacts[i]["firstName"] === name) {
//            namecheck = 1;
//        } 
//    }
  for(var i=0;i<contacts.length;i++){
    if (contacts[i].firstName==name){
      namecheck=1;
      if(contacts[i].hasOwnProperty(prop))
        return contacts[i][prop];
      else
       return "No such property" ;
    }
  if (namecheck==0)
    return  "No such contact";  
  }
// Only change code above this line
}


lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup


#2

The way which can pass.

function lookUpProfile(name, prop){

var namecheck=0;
for(var i=0; i<=contacts.length-1; i++) {
if (contacts[i][“firstName”] === name) {
namecheck = 1;
}
}
for(var i=0;i<contacts.length;i++){
if (contacts[i].firstName==name){
//namecheck=1;
if(contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
else
return “No such property” ;
}
if (namecheck==0)
return “No such contact”;
}
// Only change code above this line
}

// Change these values to test your function
lookUpProfile(“Akira”, “likes”);


#3

Well, it is far from elegant but it does the job.

Basically you are using the first loop to check if the name provided exists in the contacts array. Then in the following loop you handle the cases of the name existing with a matching prop or no matching prop as well as handling the no name match found case.
You could have, as an example, used only one for loop to do this. Maybe you can try to…


#5

Thanks for your reply.

But when I do that in one loop ,it can’t pass the challenge.And I don’t know the reason.
You can compare the first way which can’t pass with the second way which can pass.


#6

Remove the first if block from the first answer. Then run through the logic of the loop. And remember that a return inside a loop exits the function. You’ll find your answer there.


#7

Here is another tip for you. Can a human being do this task without looping twice through the list? ( ie. if someone gave you this job would you need to do it the way you wrote it? Imagine a list of 3000 contacts when you answer. Would you even want to loop twice?)