-2

I tried this method in an array to get min and max values but it doesn't work.

var array = [3, 6, 1, 5, 0, -2, 3];
var min = Math.min( array ); 
var max = Math.max( array ); 
document.write(max);
helloflash
  • 2,457
  • 2
  • 15
  • 19

2 Answers2

4

Use Function.apply

min = Math.min.apply(null, array);
min = Math.max.apply(null, array);

apply is very similar to call(), except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

Try this.

function minmax(){
  var max = Math.max.apply(Math, arguments);
  var min = Math.min.apply(Math, arguments);
  console.log(max);  // print 6
  console.log(min); // print -2
}
minmax (3, 6, 1, 5, 0, -2, 3);
Gopal
  • 461
  • 5
  • 6