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
both produces the following error in Node.js.A more robust solution is to not add every element to the call stack, but to instead pass an array:
If you are concerned about speed, the following code is ~3 times faster then
Math.max.apply
is on my computer. See http://jsperf.com/min-and-max-in-array/2.If your arrays contains strings instead of numbers, you also need to coerce them into numbers. The below code does that, but it slows the code down ~10 times on my machine. See http://jsperf.com/min-and-max-in-array/3.
Using spread operator (ES6)
Math.min & Math.max
The
Math.min
andMath.max
are both recursive operations which most likely crach for big arrays (greater than ~10⁷ items).Instead, you can use old javascript loops like so:
Or (better run-time):
* Tested with 1,000,000 items:
Just for a reference, the 1st function run-time (on my machine) was 15.84ms vs 2nd function with only 4.32ms.
Using
Math.max()
orMath.min()
The following function uses
Function.prototype.apply()
to find the maximum element in a numeric array.getMaxOfArray([1, 2, 3])
is equivalent toMath.max(1, 2, 3)
, but you can usegetMaxOfArray()
on programmatically constructed arrays of any size.Or with the new spread operator, getting the maximum of an array becomes a lot easier.
I like Linus's reduce() approach, especially for large arrays. But as long as you know you need both min and the max, why iterate over the array twice?
Of course, if you prefer the iterative approach, you can do that too:
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max
this worked for me.