Sukumar Dhoni Sukumar Dhoni - 1 month ago 7
Javascript Question

how to get the max five values from an array in Javascript?

hi i am new to angularjs , here i need highest five values in that array instead of only one max value. i had tried but i am getting only one max value.

here is my code.



var arr = [3, 4, 12, 1, 0, 5,22,20,18,30,52];
var max = arr[0];
var maxValues = [];
for (var k = 1; k < arr.length; k++) {
if (arr[k] > max) {
max = arr[k]; // output is 52
//do some thing to push max five values ie 52,30,22,20,18
}
}
console.log("Max is: " + max);
console.log("total five max values is: " + maxValues);expected output[52,30,22,20,18];

Answer

You can do it like this:

var arr = [3, 4, 12, 1, 0, 5,22,20,18,30,52];
arr = arr.sort(function (a, b) {  return a - b; });
arr = arr.slice(Math.max(arr.length - 5, 0))
console.log(arr);

First you sort the array from smallest to biggest. Then you get the last 5 elements from it, which are the biggest ones.