Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Get top 5 max elements from array

How can I get top 5 max elements from array of ints with the standard library of es2015? Thanks for help.

like image 551
Dmitriy Kovalenko Avatar asked Aug 31 '16 16:08

Dmitriy Kovalenko


People also ask

How do you find the first three elements of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.


2 Answers

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); // [789,689,98,65,33]

Many others exist, ask if you need more

like image 129
kevin ternet Avatar answered Sep 28 '22 10:09

kevin ternet


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

[11, 10, 8, 6, 2]

like image 5
Cody Moniz Avatar answered Sep 28 '22 12:09

Cody Moniz