Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the min/max element of an array in JavaScript

Tags:

javascript

How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

let array = [100, 0, 50]  array.min() //=> 0 array.max() //=> 100 
like image 212
HankH Avatar asked Nov 03 '09 18:11

HankH


People also ask

How do you find the lowest and highest value in JavaScript?

To get the highest or lowest number from an array in JavaScript, you can use the Math. max() or the Math. min() methods then spread the elements from the array to these methods using the spread operator ( ... ). Both the methods Math.


2 Answers

How about augmenting the built-in Array object to use Math.max/Math.min instead:

Array.prototype.max = function() {   return Math.max.apply(null, this); };  Array.prototype.min = function() {   return Math.min.apply(null, this); }; 

Here is a JSFiddle.

Augmenting the built-ins can cause collisions with other libraries (some see), so you may be more comfortable with just apply'ing Math.xxx() to your array directly:

var min = Math.min.apply(null, arr),     max = Math.max.apply(null, arr); 

Alternately, assuming your browser supports ECMAScript 6, you can use the spread operator which functions similarly to the apply method:

var min = Math.min( ...arr ),     max = Math.max( ...arr ); 
like image 144
Roatin Marth Avatar answered Sep 22 '22 17:09

Roatin Marth


var max_of_array = Math.max.apply(Math, array); 

For a full discussion see: http://aaroncrane.co.uk/2008/11/javascript_max_api/

like image 40
newspire Avatar answered Sep 19 '22 17:09

newspire