Question

I want to know is there any easy to get the N max/min number with Javascript.

For example:

Give [3,9,8,1,2,6,8]

Want the Max 3 elements

Will return [9,8,8]
Was it helpful?

Solution

Maybe something like this,

var numbers = [3,9,8,1,2,6,8].

numbers.sort(function(a, b) {
    return a - b;
}).slice(-3); // returns [8, 8, 9]

More info on Array.sort here, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

OTHER TIPS

The easy way is to sort array and than get 3 last or first numbers

// initial array
var a = [ 5, 2, 6, 10, 2 ];

// you need custom function because by default sort() is alphabetic 
a.sort(function(a,b) { return a - b; });

// smallest numbers
console.log(a.slice(0,3));

// biggest numbers
console.log(a.slice(-3));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top