문제

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]
도움이 되었습니까?

해결책

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

다른 팁

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top