JS - Get top 5 max elements from array
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]
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
[2, 6, 8, 1, 10, 11].sort((a, b) => b - a).slice(0,5)
[11, 10, 8, 6, 2]
"number of code lines" efficient code already mentioned in other answers, here is algorithm for better runtime and memory efficiency:
If you can modify input array in place: partition it recursively until your pivot is exactly at 5th position. This approach has linear time average complexity.
Another approach (does not requires modification of input array):
Use max heap tree, iterate over all elements in the input array, on every step insert element into heap tree and remove smallest element from heap if it contains more than 5 elements. This algorithm has N*log(5) running time so again, linear compared to the input array size