AndrewLeonardi AndrewLeonardi - 1 year ago 41
Javascript Question

Get highest 3 numbers from an array?

The code below returns the highest number from the array. I am attempting to figure out how to get the top 3 numbers from the array and have been unable to figure it out.

I also am trying to figure out how to list the corresponding jobs with their scores. At the moment the H1 with "Your Highest score was" only shows the number and does not pass through the job (or var name for the highest number).

Any thoughts on how to accomplish this?



<h3> Job 95- <span id="score95"> </span> </h3>
<h3> Job 96- <span id="score96"> </span> </h3>
<h3> Job 97- <span id="score97"> </span> </h3>
<h3> Job 98- <span id="score98"> </span> </h3>
<h3> Job 99- <span id="score99"> </span> </h3>
<h3> Job 100- <span id="score100"> </span> </h3>
<h1> Your highest score was: <span id="highest"></span></h1>


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

$( "#no15" ).click(function() {
job95 += 10;
job96 += 20;
job97 += 30;
job98 += 40;
job99 += 50;
job100 += 60;

var numArray = [job95,job96, job97, job98, job99,job100]

Answer Source

Sort from lowest to highest and then slice. Example:

var arr = [1, 3, 2, 1, 5, 6, 3];
//Sort the array from lowest to highest
//Thanks to Charlietfl, I forgot to sort it numerically
arr.sort(function(a, b) {
  return a - b;
//Get the highest 3
var top3Arr = arr.slice(-3);

//This is an array, so if you want each number individually just access the array

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