How can I easily obtain the min or max element of a JavaScript Array?
Example Psuedocode:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
How can I easily obtain the min or max element of a JavaScript Array?
Example Psuedocode:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
I am surprised not one mentiond the reduce function.
Simple stuff, really.
I thought I'd share my simple and easy to understand solution.
For the min:
And for the max:
Others have already given some solutions in which they augment
Array.prototype
. All I want in this answer is to clarify whether it should beMath.min.apply( Math, array )
orMath.min.apply( null, array )
. So what context should be used,Math
ornull
?When passing
null
as a context toapply
, then the context will default to the global object (thewindow
object in the case of browsers). Passing theMath
object as the context would be the correct solution, but it won't hurt passingnull
either. Here's an example whennull
might cause trouble, when decorating theMath.max
function:The above will throw an exception because
this.foo
will be evaluated aswindow.foo
, which isundefined
. If we replacenull
withMath
, things will work as expected and the string "foo" will be printed to the screen (I tested this using Mozilla Rhino).You can pretty much assume that nobody has decorated
Math.max
so, passingnull
will work without problems.One more way to do it:
Usage:
Two ways are shorter and easy: