yuyue007
yuyue007

Reputation: 1269

Get max N numbers in an array with Javascript

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]

Upvotes: 1

Views: 2582

Answers (2)

lostsource
lostsource

Reputation: 21830

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

Upvotes: 7

Artem Petrosian
Artem Petrosian

Reputation: 2954

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));

Upvotes: 3

Related Questions