Home > Mobile >  how do I wrap a piece of code inside a function?
how do I wrap a piece of code inside a function?

Time:12-18

I have this code written:

for(var i = 0; i < family.length; i  ) {
      console.log(family[i].name) 
      console.log(`${family[i].name} has the following friends:${family[i].friends}`) 
    }

it actually go thorough each family member (all defined as objects) and displays the first name of the family member and then his friends...

Now I want to wrap it in a function which prompts the user to enter a family member, if it exists it does as above, if not it alerts the user that the member is not listed and you need to add it as another object. So I did this:

let input = window.prompt("Enter a name of a family member");

  function member() {
  
  if (input === family[family.name]) {

    for(var i = 0; i < family.length; i  ) {
      console.log(family[i].name) 
      console.log(`${family[i].name} has the following friends:${family[i].friends}`) 
    }
}
  else {
    alert("This family member is not in my list - please add him");

  }
  
}

but is does not work...what am I doing wrong?

CodePudding user response:

You need to add a way to execute member();

I would execute member(); after submitting the input.

CodePudding user response:

You need to loop and actually call the function

const family = [{
    name: "fred",
    friends: [{
      name: "frank"
    }]
  },
  {
    name: "frank",
    friends: [{
      name: "fred"
    }]
  }
]

function member(input) {
  const found = family.filter(({name}) => name.includes(input));
  if (found.length) found.forEach(person => console.log(person.name,`has the following friends: ${person.friends.map(friend => friend.name).join(', ')}`))
  else {
    console.log("This family member is not in my list - please add him");
  }
}

let input = window.prompt("Enter a name of a family member");
member(input)

  • Related