-
-
Save anonymous/ef454b216b7d8560a2fd3d1bfa54f655 to your computer and use it in GitHub Desktop.
Is there a more efficient way to access the array of object?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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" | |
*/ | |
//Setup array of objects | |
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) { | |
/* | |
Input first name and property. | |
Return: | |
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" | |
else Return "prop" relating to firstName. | |
Assumptions: All firstnames are unique | |
*/ | |
let loop = 0; | |
let result = "No such contact"; | |
let firstNameFound = false; | |
for(loop; loop < contacts.length; loop++){ | |
if (contacts[loop].firstName == firstName){ | |
firstNameFound = true; | |
break; | |
}; | |
}; | |
if ((firstNameFound == true) && (contacts[loop][prop] == undefined)){ | |
result = "No such property"; | |
} else if((firstNameFound == true) && (contacts[loop][prop] != undefined)) { | |
result = contacts[loop][prop]; | |
}; | |
return(result); | |
}; | |
//Test Cases | |
console.log(lookUpProfile("Andrew", "likes")); // no such contact | |
console.log(lookUpProfile("Akira", "likes")); // array returned | |
console.log(lookUpProfile("Sherlock", "likes")); // array returned | |
console.log(lookUpProfile("Kristian", "lastName" )); // vos | |
console.log(lookUpProfile("Kristian", "address" )); // no such property |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment