AndrewLeonardi AndrewLeonardi - 4 months ago 7
Javascript Question

Display multiple parts of an object?

This object gives the score and the job name:

var job0= {
score: 100,
name: "Project Manager"
}


$('#scoreTest').text(job0.score +' ' + job0.name)


I'm attempting to have jobs 96-100 also be objects with job names and scores as above. The issue is I have been unable to pass the job name through the array to find the 3 highest scores utilizing the object strategy above. I am only able to pass the score #'s through. How would I pass the job name through so #highest1, #Highest2, #Highest3 would also show the job name?

var job95 = 100;
var job96 = 100;
var job97 = 100;
var job98 = 100;
var job99 = 100;
var job100 = 100;


var numArray = [job95,job96, job97, job98, job99,job100]
$('#highest').html(Math.max.apply(Math,numArray));

numArray.sort(function(a, b) {
return a - b;
});
//Get the highest 3
var top3Arr = numArray.slice(-3);

var firsthighest = top3Arr[2] ;
var secondHighest = top3Arr[1];
var thirdHighest = top3Arr[0];

$('#highest1').html(firsthighest +' '+ job0.name)
$('#highest2').html(secondHighest)
$('#highest3').html(thirdHighest)
});

Answer

You could use direct an array for the objects.

var jobs = [{
        score: 10,
        name: "Project Manager"
    }, {
        score: 20,
        name: "Team Leader"
    }, {
        score: 42,
        name: "Worker"
    }, {
        score: 99,
        name: "Worker"
    }, {
        score: 100,
        name: "Worker"
    }],
    top3;

jobs.sort(function (a, b) { return b.score - a.score; });
top3 = jobs.slice(0, 3);

console.log(top3);

Comments