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]