Find the min/max element of an Array in JavaScript

2018-12-31 01:11发布

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

标签: javascript
30条回答
孤独寂梦人
2楼-- · 2018-12-31 01:46

For big arrays (~10⁷ elements), Math.min and Math.max procuces a RangeError (Maximum call stack size exceeded) in node.js.

For big arrays, a quick & dirty solution is:

Array.prototype.min = function() {
    var r = this[0];
    this.forEach(function(v,i,a){if (v<r) r=v;});
    return r;
};
查看更多
零度萤火
3楼-- · 2018-12-31 01:48
minHeight = Math.min.apply({},YourArray);
minKey    = getCertainKey(YourArray,minHeight);
maxHeight = Math.max.apply({},YourArray);
maxKey    = getCertainKey(YourArray,minHeight);
function getCertainKey(array,certainValue){
   for(var key in array){
      if (array[key]==certainValue)
         return key;
   }
} 
查看更多
皆成旧梦
4楼-- · 2018-12-31 01:48

A simple solution to find the minimum value over an Array of elements is to use the Array prototype function reduce:

A = [4,3,-9,-2,2,1];
A.reduce((min, val) => val < min ? val : min, A[0]); // returns -9

or using JavaScript's built-in Math.Min() function (thanks @Tenflex):

A.reduce((min,val) => Math.min(min,val), A[0]);

This sets min to A[0], and then checks for A[1]...A[n] whether it is strictly less than the current min. If A[i] < min then min is updated to A[i] by returning this value.

查看更多
墨雨无痕
5楼-- · 2018-12-31 01:49

You can use the following function anywhere in your project:

function getMin(array){
    return Math.min.apply(Math,array);
}

function getMax(array){
    return Math.max.apply(Math,array);
}

And then you can call the functions passing the array:

var myArray = [1,2,3,4,5,6,7];
var maximo = getMax(myArray); //return the highest number
查看更多
几人难应
6楼-- · 2018-12-31 01:52
var max_of_array = Math.max.apply(Math, array);

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

查看更多
浪荡孟婆
7楼-- · 2018-12-31 01:53

You do it by extending the Array type:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
}; 

Boosted from here (by John Resig)

查看更多
登录 后发表回答