7/8 "Search for a friend" problem


#1

Chapter 6, "Contact List" Lesson, #7 of 8

I've reached the point where I'm trying to make a function named search, found at the bottom of my code. When I try it, it says "Oops, try again. It looks like your search function doesn't return contact information for Steve."

I can tell that I need to find the firstName values in the bill and steve arrays, but how can I get the function to identify these values when I have to start with the friends array and only using the for/in tool.

PS - I'm still learning the basics about coding, so forgive me as I butcher the proper terms.

var friends = {
     bill: {
          firstName: "Bill",
          lastName: "Nye",
          number: "987654321",
          address: ["Blah","Blah","Blah"]
     },
     steve: {
          firstName: "Steve",
          lastName: "Jobs",
          number: "123456789",
          address: ["Blah","Blah","Blah"]
     }
}

var list = function(parameter) {
     for (var firstName in friends) {
     console.log(key)
     }
}

/*Below is my problem*/
var search = function(name) {
     for (var firstName in friends) {
          if (name === firstName) {
               console.log(friends);
               return friends
          }
     }
}

#2

The for in loops through the properties of an object
firsName is first bill and second steve

1.
friends["bill"].firstName (Bill)

2.
friends["steve"].firstName (Steve)

If we know that, we can do that

friends[firstName].firstName === name


#3

Thanks, that helped a lot. I ended up using the code below for the "search" function, and the website accepted it:

var search = function(name) {
     if (friends["bill"].firstName === name) {
          console.log(friends["bill"]);
          return friends["bill"]
          }
     if (friends["steve"].firstName === name) {
          console.log(friends["steve"]);
          return friends["steve"]
          }
     }

#4

Accepted, but wrong!

Think about what happend if we get new or more propertys called "David","Joshua","Simon" in our friends object. Do you wanna add three more ifs?

No you didnt :slight_smile:

You want it dynamiclly like this

var search = function(name) {
     for (var firstName in friends) {
          if (friends[firstName].firstName == name) {
               return friends[name];
          }
     }
 }

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.