JS - Get top 5 max elements from array

2020-03-30 03:01发布

问题:

How can I get top 5 max elements from array of ints, which in its turn is a property of js object. Thanks for help.

回答1:

A solution in ES6 :

values = [1,65,8,98,689,12,33,2,3,789];
var topValues = values.sort((a,b) => b-a).slice(0,5);
console.log(topValues); // [ 1, 2, 3, 8, 12 ]

Many others exist, ask if you need more



回答2:

[2, 6, 8, 1, 10, 11].sort((a, b) => b - a).slice(0,5)

[11, 10, 8, 6, 2]



回答3:

Although above approach by @Kevin and @Cody is correct, it would also change the original array which might affect your code. I would recommend to copy the array first, and then perform sort. As your array is of ints only, we can shallow copy it. To do so, you can use spread operator :

values = [1,65,8,98,689,12,33,2,3,789];
var topValues = [...values].sort((a,b) => b-a).slice(0,5); 
// [...values] will create shallow copy
console.log(topValues); // [789, 689, 98, 65, 33]