I spent a few hours trying to solve this exercise by writing for loops, but for some reason I couldn’t get it to work. Then I looked up online to see if there were other methods that could achieve the same end. Finally, after some more head-scratching, I came up with an answer:
function lookUpProfile(name, prop){
// Only change code below this line
var index = contacts.findIndex(x => x.firstName == name);
var value = contacts.find(x => x.firstName == name);
if(index == -1) {
return "No such contact";
} else if (index > - 1) {
if(value.firstName && value.hasOwnProperty(prop)) {
return value[prop];
} else if (value.firstName && value.hasOwnProperty(prop) == false) {
return "No such property";
}
}
}
After I passed the test, I checked out the answer on the website, knowing that they would use a for loop and that the answer would be much simpler than mine. Now I think I understand how both solutions work.
What I wanted to understand a little bit better is this: what are the differences between using a for loop here instead of using the array.find()
and array.findIndex()
functions? Is there an advantage to the loop in this case, besides being simpler? Is my solution ok?
Thanks.