Where this previous article explained how to get the max number in an numeric array:
JavaScript: How to get the largest number in an array using Math.max( )
There are times where we want more than just the single highest value in an array. What if we want the top 2, 3 or 5 numbers in the array? This is a common scenario where there are multiple entrants in a contest and we want to find the top three scores to award first, second, and third places. This article will detail how to get more than one top value from a list, in an array, sorted in ascending order.
Here is some code in one line that demonstrates how to get the top 3 scores in an array:
console.log([1, -5, 22, 8, 17, 0, -2].sort(function(a, b){return b - a}).slice(0, 3));
Which yields:
[22, 17, 8]
Written another way, assigning the results to a new list:
let scores = [1, -5, 22, 8, 17, 0, -2]; let winners = scores.sort( function(a, b){return b - a}).slice(0, 3)); console.log("Winners:", winners);
There are three parts to this:
Part 1: array
[1, -5, 2, 8, 17, 0, -2]
Part 2: .sort( )
sort() has one argument and it is a function with arguments a and b
.sort(function(a, b){return b - a})
Part 3: .slice( )
slice() takes a portion of the list that has just been sorted in ascending order by the .sort function. The first argument for .slice is the starting index, and the second argument is the number of top values to return (in order, from largest to smallest).
.slice(0, 3)
Now to get the N largest numbers in an array, all we have to do is replace the 3 in the slice argument with n. For example:
let nums = [4, 3, 3, 3, 0, 4, 3, 0, 3, 34, 0, 11, 32, 0]; let n = 5; let topFive = nums.sort(function(a, b){return b - a}).slice(0, n); console.log('topFive', topFive);
which yields:
"topFive" [34, 32, 11, 4, 4]
For more information about the .sort() and .slice() methods, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort