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

Posted by meo on Stack Overflow See other posts from Stack Overflow or by meo
Published on 2010-05-17T21:58:13Z Indexed on 2010/05/17 22:10 UTC
Read the original article Hit count: 244

Filed under:

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?

© Stack Overflow or respective owner

Related posts about JavaScript