How to solve the problem more elegantly?

How to solve the problem more elegantly?
0.0 0

#1

profile-lookup

my solution looks like this:


//Setup
var contacts = [
{
“firstName”: “Akira”,
“lastName”: “Laine”,
“number”: “0543236543”,
“likes”: [“Pizza”, “Coding”, “Brownie Points”]
},
{
“firstName”: “Harry”,
“lastName”: “Potter”,
“number”: “0994372684”,
“likes”: [“Hogwarts”, “Magic”, “Hagrid”]
},
{
“firstName”: “Sherlock”,
“lastName”: “Holmes”,
“number”: “0487345643”,
“likes”: [“Intriguing Cases”, “Violin”]
},
{
“firstName”: “Kristian”,
“lastName”: “Vos”,
“number”: “unknown”,
“likes”: [“Javascript”, “Gaming”, “Foxes”]
}
];

function lookUpProfile(firstName, prop){
// My solution

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

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

}

for (var j = 0; j <= contacts.length-1; j++) {

if (contacts[j].firstName !== firstName) {
  return "No such contact";
}

}

// My solution

}

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


what is more beautiful decision?


#2

I’m not sure if this is more beautiful, but this was my solution:

function lookUpProfile(firstName, prop){
  var ans=-1;
  
contacts.forEach(function(data){
  if(data.firstName==firstName)
    {
      if(data[prop]!==undefined) ans=data[prop];
      else return "No such property";
    }
});
  
  if(ans==-1) return "No such contact";
  else return ans;
}

#3

thank you for your solution


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

}  
// Only change code above this line
}