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
For big arrays (~10⁷ elements),
Math.min
andMath.max
procuces a RangeError (Maximum call stack size exceeded) in node.js.For big arrays, a quick & dirty solution is:
A simple solution to find the minimum value over an
Array
of elements is to use theArray
prototype functionreduce
:or using JavaScript's built-in Math.Min() function (thanks @Tenflex):
This sets
min
toA[0]
, and then checks forA[1]...A[n]
whether it is strictly less than the currentmin
. IfA[i] < min
thenmin
is updated toA[i]
by returning this value.You can use the following function anywhere in your project:
And then you can call the functions passing the array:
For a full discussion see: http://aaroncrane.co.uk/2008/11/javascript_max_api/
You do it by extending the Array type:
Boosted from here (by John Resig)