简体   繁体   中英

What is the most efficient way to get the highest and the lowest values in a Array

is there something like PHP: max() in javascript?

lets say i have an array like this:

[2, 3, 23, 2, 2345, 4, 86, 8, 231, 75]

and i want to return the highest and the lowest value in this array. What is the fastest way to do that?

i have tried:

function madmax (arr) {
  var max = arr[0],
      min = arr[1]

  if (min > max) {
      max = arr[1]
      min = arr[0]   
  }

  for (i=1;i<=arr.length;i++){
     if( arr[i] > max ) {
       max = arr[i]
     }else if( arr[i] < min ) {
       min = arr[i]
     }
}

return max, min
}

madmax([123, 2, 345, 153, 5, 98, 456, 4323456, 1, 234, 19874, 238, 4])

Is there a simpler way retrieve the max and min value of a array?

Applying the Math.max and Math.min built-in methods can be really fast:

var array = [2, 3, 23, 2, 2345, 4, 86, 8, 231, 75];
var max = Math.max.apply(Math, array); // 2345
var min = Math.min.apply(Math, array); // 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM