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()
Using Math.max()
or Math.min()
Math.max(10, 20); // 20
Math.min(-10, -20); // -20
The following function uses Function.prototype.apply()
to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3])
is equivalent to Math.max(1, 2, 3)
, but you can use getMaxOfArray()
on programmatically constructed arrays of any size.
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
Or with the new spread operator, getting the maximum of an array becomes a lot easier.
var arr = [1, 2, 3];
var max = Math.max(...arr); // 3
var min = Math.min(...arr); // 1