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
Here's one way to get the max value from an array of objects. Create a copy (with slice), then sort the copy in descending order and grab the first item.
tl;dr
Official
Math.max()
MDN documentationThis may suit your purposes.
Iterate through, keeping track as you go.
This will leave min/max null if there are no elements in the array. Will set min and max in one pass if the array has any elements.
You could also extend Array with a
range
method using the above to allow reuse and improve on readability. See a working fiddle at http://jsfiddle.net/9C9fU/Used as
If you're paranoid like me about using
Math.max.apply
(which could cause errors when given large arrays according to MDN), try this:Or, in ES6:
The anonymous functions are unfortunately necessary (instead of using
Math.max.bind(Math)
becausereduce
doesn't just passa
andb
to its function, but alsoi
and a reference to the array itself, so we have to ensure we don't try to callmax
on those as well.ChaosPandion's solution works if you're using protoype. If not, consider this:
The above will return NaN if an array value is not an integer so you should build some functionality to avoid that. Otherwise this will work.