freeCodeCamp Challenge Guide: Profile Lookup

freeCodeCamp Challenge Guide: Profile Lookup
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: Problem Explanation:

We have an array of objects representing different people in our contacts lists.

A lookUpProfile() function that takes firstName and a property (prop) as arguments has been pre-written for you.

The function should check if firstName is an actual contact’s firstName and the given property (prop) is a property of that contact.

If both are true, then return the value of that property.

If firstName does not correspond to any contacts then return No such contact.

If prop does not correspond to any valid properties then return No such property.

  • Change the code below // Only change code below this line and up to // Only change code above this line.
  • Ensure that you are editing the inside of the lookUpProfile() function.
    • This function includes two parameters, firstName and prop.
  • The function should look through the contacts list for the given firstName parameter.
    • If there is a match found, the function should then look for the given prop parameter.
    • If both firstName and the associated prop are found, you should return the value of the prop.
    • If firstName is found and no associated prop is found, you should return No such property.
  • If firstName isn’t found anywhere, you should return No such contact.

Relevant Links

:speech_balloon: Hint: 1

Use a for loop to cycle through the contacts list.

try to solve the problem now

:speech_balloon: Hint: 2

Use a nested if statement to first check if the firstName matches, and then checks if the prop matches.

try to solve the problem now

:speech_balloon: Hint: 3

Leave your return "No such contact" out of the for loop as a final catch-all.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution:

for (var x = 0; x < contacts.length; x++){
    if (contacts[x].firstName === firstName) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        } else {
            return "No such property";
        }
    }
}
return "No such contact";

Code Explanation:

  • The for loop runs, starting at the first object in the contacts list.
  • If the firstName parameter passed into the function matches the value of the "firstName" key in the first object, the if statement passes.
  • Then, we use .hasOwnProperty() method (checks if there’s a given property and returns a boolean) with prop as an argument. If it’s true, the value of prop is returned.
    • If the second if statement fails, No such property is returned.
  • If the first if statement fails, the for loop continues on to the next object in the contacts list.
  • If the firstName parameter isn’t matched by the final contacts object, the for loop exits and No such contact is returned.

Example Run

  • lookUpProfile("Akira","likes"); runs.
  • "Akira" is matched to the "firstName" key in the first object, so the if statement returns true.
  • "likes" is found within the first object, so the second if statement returns true.
  • The value of "likes" is returned - "Pizza", "Coding", "Brownie Points".

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


What is the explanation for the For Loop in the profile Lookup exercise?
Why is my "Profile Lookup" challenge code not working?
What is the explanation for the For Loop in the profile Lookup exercise?
Profile Lookup, no se que hago mal en este codigo
Why is this code not return true?
#2

I did something like this

function lookUpProfile(firstName, prop) {    
    var result = contacts.filter(x => x.firstName == firstName)

    if (result.length === 0) {
        return "No such contact";
    } else {
        return result[0][prop] ? result[0][prop] : "No such property";
    }
}

or

function lookUpProfile(firstName, prop) {
    let contact = contacts.find((x) => x.firstName === firstName)
    return contact ? contact.hasOwnProperty(prop) ? contact[prop] : "No such property" : "No such contact”;
}

#3

I just refactored mine today and my solution is very close to your 2nd solution. I used filter, but I like your use of find better.

function lookUpProfile(name, prop){
  const fnMatch = contacts.filter(cont => cont.firstName === name);
  return fnMatch.length ? (fnMatch[0][prop] ? fnMatch[0][prop] : "No such property") : "No such contact";
}

#4

The firstName variable inside the lookup function should be changed to anyName, or even just Name.

Edit: Better yet, just use myName and myProp as in the lessons before.


#6

Man, I really feel like an idiot. I spent a couple of hours trying to figure this out, just to find that one of my return statements was out of place. Here my original code:

for (i = 0; i < contacts.length; i++) {
if (firstName === contacts[i].firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return “No such property”;
}
} else {
return “No such contact”;
}
}

So, I just learned the hard way that I need to loop through each index before returning anything.


#7

I did the exact same code as you, don’t feel so bad - or to put it another way, we are both idiots, lol.


#8

I’m confused in the return line here :
return contacts[i][prop];
why it doesn’t work when i replace the brackets notation with the dot. linking, since both ways are valid.
I mean like this
return contacts[i].prop;


#9

Same problem here…


#10

for(var i=0;i<4;i++) {
if(firstName === contacts[i].firstName && prop === contacts[i].prop)
return contacts[i].prop;
else if (firstName != contacts[i].firstName)
return “No such contact”;
else
return “No such property”;
}

I could not figure out a mistake in my code. Is there something that I am missing?


#11

I did this soluction. My code is not beaultiful, but it works.

function lookUpProfile(firstName, prop){
// Only change code below this line

var checkFirstName = false;

for(var i=0;i<contacts.length;i++){

if(contacts[i].firstName===firstName){
  checkFirstName = true;
  if(contacts[i].hasOwnProperty(prop)===false){
    return "No such property";
  } else {
    return contacts[i][prop];
  }
}

}

if(checkFirstName === false){
return “No such contact”;
}


#12

This is what I used, but I was getting an error code telling me to write != as !== which does not work. I almost used the hasOwnProperty() method but I was having a hard time making that work and this worked. I feel like there might just be a bug with the editor telling me this is wrong, does anyone have any ideas why this would be happening.

for(i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == firstName) {
if(contacts[i][prop] != null) {
return contacts[i][prop];
} else return “No such property”;
}
}
return “No such contact”;


#13

@AhmedMJ @KshitijaaJaglan

contacts[i][prop]
vs
contacts[i].prop

  • We cannot called contacts[i].prop because.prop is not a property of contacts.

  • When we access objects in bracket notation contacts[i][prop], we can read and pass in values, such as the function arguments (example: “lastName”, “likes”, “numbers”, etc.)

function lookUpProfile(firstName, prop) 

contacts[i][prop] can pass in prop argument:
lookUpProfile("Kristian", "lastName");

var property = contacts[i]["lastName"];
property = "Vos";


#14
function lookUpProfile(firstName, prop) {
                 for(var i=0;i<4;i++) {
                if(firstName === contacts[i].firstName && prop === contacts[i].prop)
                return contacts[i].prop;
                else if (firstName != contacts[i].firstName)
                return "No such contact";
                else
                return "No such property";
                }
            }

    lookUpProfile("Kristian", "lastName")

for(var i=0;i<4;i++)

  • You should not use static number 4, and instead call the array’s .length.

if(firstName === contacts[i].firstName && prop === contacts[i].prop)

  • contacts[i].prop will not call the prop argument passed in, "lastName".
  • contacts[i].prop will call contacts[i] property named "prop", which it does not have.
  • You want contact[i] to call "lastName" property, which is accessible by calling contact[i]["lastName"].
  • That is why we use contact[i][prop].

I would recommend checking for firstName logic seperately from prop - that will help. There are also syntactical errors (curly braces), use them :slight_smile:


#15

I did the same thing lol, but at least it was only 15 mins wasted ><


#17

Hi guys, It took me the whole day and I think I am fully idiot for now because it still doesn’t work will. Here is the Code:

function lookUpProfile(first, prop){
var result = “”;
var contactTest = “firstName”;
var propTest1 = “lastName”;
var propTest2 = “number”;
var propTest3 = “likes”;

for (var i=0; i<= contacts.length; i++){
var testName = contacts[i][contactTest];
if (first === testName){
switch (prop){
case “lastName”:
result = contacts[i][propTest1];
break;
case “number”:
result = contacts[i][propTest2];
break;
case “likes” :
result = contacts[i][propTest3];
break;
default:
result = “No Such Property”;
}
}else {

result = “No Such Contact”;
}
}
return result ;

}
lookUpProfile(“Harry”, “number”);
/* main concept
if firstname exsits >>> check for property >>> if it exsiting … return its value
if Not … return no such property
if firstname isn’t exsiting >>> no such contact
*/

it gives me an error of (( Can’t read property ‘firstName’ of undefined )) !!
what’s wrong now ?!


#18

It took me like 5 hours to understand that i had to put the return " No such contact" out of my loop
^^.

for (var i = 0; i < contacts.length; i++)

{

 if  (firstName == contacts[i].firstName && contacts[i].hasOwnProperty(prop))  
 
      {
        
        return contacts[i][prop] ;
           
      }     
 
 if (!(contacts[i].hasOwnProperty(prop))) 
     
      { 
        
       return "No such property";      
      }     

}

return “No such contact”;


#20

Hi…So awesome to see everyone’s creativity.
It took me two days so I am satisfied.
Please share your thoughts on the code…

function lookUpProfile(firstName, prop){
    var value;
    for (var i = 0; i < contacts.length; i++){
      if((contacts[i].firstName === firstName) && 
         (contacts[i].hasOwnProperty(prop))){
        value = contacts[i][prop];
        break;
    }
    if (contacts[i].hasOwnProperty(firstName) === false){
      value = "No such contact";
    }
    if (contacts[i].hasOwnProperty(prop) === false) {
      value = "No such property";
    }
    }
    return value;
    }

#21

First time poster! One question, going off the basic code solution is their an alternative way to check if the prop argument matches the property of the object besides using "

if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return “No such property”;
" .

I can’t wrap my head around why this other alternative method would not work.
if(contacts[i][prop]===prop){
return contacts[i][prop];
}
else{
return “No such property”;
}


#22

I just realized that this example is following

contacts is an array of objects. So .length is only for the properties of an array

likes is also an array as well

.hasOwnProperty is a property of an object.

Also for original solution

return contacts[x][prop];

am not sure why this doesn’t work

return contacts[x].prop;

Using

return contacts[x].likes;

returns this

I think the program cannot tell whether its a variable that its being passed or an actual property of the object using dot notation

stackoverflow says this is correct

To understand the context of this, you can convert firstName into bracket notation which requires a quotation marks (from original solution)

following code works

function lookUpProfile(firstName, prop){
// Only change code below this line
  for (var x =0; x<contacts.length; x++){
    if (contacts[x]["firstName"] === firstName){
      if (contacts[x].hasOwnProperty(prop)){
        return contacts[x][prop];
      } else {
      return "No such property";
      }
    }
    
  }
return "No such contact";
// Only change code above this line
}

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

In summary, you should use bracket notation

  • when property name is contained in a variable, in this case prop, but not firstName (the variable being passed to function, the property of the object “firstName” is ok though) → this is confusing how the program named it, these should’ve been different names.

  • Property name contains characters not permitted in identifiers (Space, - ↑ unicode symbols, etc)

else use dot notation

see this stackoverflow post:


#23

Alternative solution without using hasOwnProperty but rather a for ....in loop

function lookUpProfile(firstName, prop){
// Only change code below this line
  for (var x =0; x<contacts.length; x++){
    if (contacts[x].firstName === firstName){
        for (var keys in contacts[x]){
          if (keys === prop){
            return contacts[x][prop];
          } 
        } 
        return "No such property";
      }
    }  
return "No such contact";
}