Sukumar MS
Sukumar MS

Reputation: 758

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];

Upvotes: 0

Views: 2287

Answers (4)

You can use ES6 array methods to convert your solution to a one-liner.

let arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52];

//Required to get five maximum numbers of an array
const getFiveMaxNums = array => array.sort((a, b) => b - a).slice(0, 5);
console.log(getFiveMaxNums(arr));

//you can further modify the function to become more re-usable and return 'n' maximum numbers for any given array with array.lenght >= n;
const getMaxNums = (array, n) => array.sort((a, b) => b - a).slice(0, n);
console.log(getMaxNums(arr, 5));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386730

With angular, you could use limitTo.

In HTML Template Binding

{{ limitTo_expression | limitTo : limit : begin}}

In JavaScript

$filter('limitTo')(input, limit, begin)

Upvotes: 0

Rajesh
Rajesh

Reputation: 24945

You can sort it in descending order and then fetch n values using array.slice

function getMaxValues(arr, n){
  return arr.sort(function(a,b){ return b-a }).slice(0,n);
}

var arr = [3, 4, 12, 1, 0, 5,22,20,18,30,52];
console.log(getMaxValues(arr, 5))
console.log(getMaxValues(arr, 3))

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11480

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.

Upvotes: 5

Related Questions