Consider a JavaScript object with keys first, last, and score, representing a student. The values of first and last are both strings (for first and last name respectively), while the value of score is an integer.
For example: {first: "John", last: "Smitt", score: 20}
Write a JavaScript function named maxName that, given an array of such objects, returns a string consisting of the full name (first and last) of the student with the largest score.
For example:
a = [
{first: "John", last: "Smith", score: 20},
{first: "Liza", last: "Hernandez", score: 50},
{first: "Mary", last: "Jones", score: 10}];
maxName(a) //=> "Liza Hernandez"
Program Code Screenshot
Program Sample Console Input/Output Screenshot
Program Code to Copy
function maxName(obj){
// assume largest to be the first score
var largest_score_pos = 0;
// compare this to all other scores
for(var i=1;i<obj.length;i++){
if(obj[largest_score_pos].score<obj[i].score){
largest_score_pos=i;
}
}
//largest_score_pos now contains the position of the person with largest score
return obj[largest_score_pos].first+" "+obj[largest_score_pos].last;
}
a = [
{first: "John", last: "Smith", score: 20},
{first: "Liza", last: "Hernandez", score: 50},
{first: "Mary", last: "Jones", score: 10}];
console.log(maxName(a))
Get Answers For Free
Most questions answered within 1 hours.