0

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];
Sukumar MS
  • 748
  • 1
  • 10
  • 41

3 Answers3

4

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.

Ionut
  • 10,707
  • 4
  • 40
  • 69
  • Just a curious question, if you are sorting array in ascending order, what is the purpose of `Math.max`? Also, by default, array.sort, sorts in ascending order. So `arr.sort()` should be fine – Rajesh Oct 25 '16 at 10:25
  • It won't work in both of your cases you stated. If you don't use `Math.max` you it will return nothing. And `arr.sort();` will not work. – Ionut Oct 25 '16 at 10:30
1

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))
Rajesh
  • 22,581
  • 5
  • 41
  • 70
0

With angular, you could use limitTo.

In HTML Template Binding

{{ limitTo_expression | limitTo : limit : begin}}

In JavaScript

$filter('limitTo')(input, limit, begin)
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358