How can I easily obtain the min or max element of a JavaScript Array?
如何轻松获取JavaScript数组的最小或最大元素?
Example Psuedocode:
示例Psuedocode:
let array = [100, 0, 50]array.min() //=> 0array.max() //=> 100
40 个解决方案
#1
667
How about augmenting the built-in Array object to use Math.max
/Math.min
instead:
如何扩展内置数组对象以使用Math.max/Math。最小值:
Array.prototype.max = function() { return Math.max.apply(null, this);};Array.prototype.min = function() { return Math.min.apply(null, this);};
Here is a JSFiddle.
这是一个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:
增加内嵌项可能会导致与其他库的冲突(有人看到),因此您可以更轻松地直接将'ing Math.xxx()应用到您的数组中:
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:
或者,假设您的浏览器支持ECMAScript 6,您可以使用与apply方法类似的扩展操作符:
var min = Math.min( ...arr ), max = Math.max( ...arr );
#2
303
var max_of_array = Math.max.apply(Math, array);
For a full discussion see:http://aaroncrane.co.uk/2008/11/javascript_max_api/
详细讨论请参见:http://aaroncrane.co.uk/2008/11/javascript_max_api/
#3
136
For big arrays (~10⁷ elements), Math.min
and Math.max
both produces the following error in Node.js.
对大型数组(~ 10⁷元素),数学。最小值和数学。max在Node.js中都会产生以下错误。
RangeError: Maximum call stack size exceeded
RangeError:超出最大调用堆栈大小
A more robust solution is to not add every element to the call stack, but to instead pass an array:
一个更可靠的解决方案是不向调用堆栈添加所有元素,而是传递一个数组:
function arrayMin(arr) { return arr.reduce(function (p, v) { return ( p < v ? p : v ); });}function arrayMax(arr) { return arr.reduce(function (p, v) { return ( p > v ? p : v ); });}
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.
如果您关心速度,下面的代码比Math.max快大约3倍。申请在我的电脑上。见http://jsperf.com/min-and-max-in-array/2。
function arrayMin(arr) { var len = arr.length, min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min;};function arrayMax(arr) { var len = arr.length, max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max;};
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.
如果数组包含字符串而不是数字,还需要将它们强制化为数字。下面的代码可以做到这一点,但是在我的机器上,它会使代码慢下来大约10倍。见http://jsperf.com/min-and-max-in-array/3。
function arrayMin(arr) { var len = arr.length, min = Infinity; while (len--) { if (Number(arr[len]) < min) { min = Number(arr[len]); } } return min;};function arrayMax(arr) { var len = arr.length, max = -Infinity; while (len--) { if (Number(arr[len]) > max) { max = Number(arr[len]); } } return max;};
#4
84
Using spread operator (ES6)
使用扩散算子(ES6)
Math.max(...array); // the same with "min" => Math.min(...array);
const array = [10, 2, 33, 4, 5];console.log( Math.max(...array))
#5
49
If you're paranoid like me about using Math.max.apply
(which could cause errors when given large arrays according to MDN), try this:
如果你像我一样偏执地想用数学。apply(根据MDN给定大数组时可能会导致错误),尝试以下方法:
function arrayMax(array) { return array.reduce(function(a, b) { return Math.max(a, b); });}function arrayMin(array) { return array.reduce(function(a, b) { return Math.min(a, b); });}
Or, in ES6:
或者,在ES6:
function arrayMax(array) { return array.reduce((a, b) => Math.max(a, b));}function arrayMin(array) { return array.reduce((a, b) => Math.min(a, b));}
The anonymous functions are unfortunately necessary (instead of using Math.max.bind(Math)
because reduce
doesn't just pass a
and b
to its function, but also i
and a reference to the array itself, so we have to ensure we don't try to call max
on those as well.
不幸的是,匿名函数是必需的(而不是使用Math.max.bind(Math),因为reduce不仅将a和b传递给它的函数,而且还将i和一个对数组本身的引用传递给它,所以我们必须确保不会对它们调用max。
#6
42
tl;dr
var max = Math.max(...arrayOfNumbers);
Official Math.max()
MDN documentation
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.下面的函数使用function .prototype.apply()查找数值数组中的最大元素。getMaxOfArray([1,2,3])等同于数学。max(1,2,3),但是您可以在任何大小的编程构造数组中使用getMaxOfArray()。
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);
#7
34
.apply
is often used when the intention is to invoke a variadic function with a list of argument values, e.g.
.apply通常用于调用一个包含一系列参数值的变量函数,例如:
The Math.max([value1[,value2, ...]])
function returns the largest of zero or more numbers.
的数学。函数的作用是:返回0个或多个数字中最大的一个。
Math.max(10, 20); // 20Math.max(-10, -20); // -10Math.max(-10, 20); // 20
The Math.max()
method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.
max()方法不允许您传入数组。如果您有一个需要最大值的列表,您通常会使用function .prototype.apply()调用这个函数。
Math.max.apply(null, [10, 20]); // 20Math.max.apply(null, [-10, -20]); // -10Math.max.apply(null, [-10, 20]); // 20
However, as of the ECMAScript 6 you can use the spread operator:
但是,从ECMAScript 6开始,您可以使用扩展操作符:
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
扩展运算符允许在需要多个参数(用于函数调用)或多个元素(用于数组文本)的地方扩展表达式。
Using the spread operator, the above can be rewritten as such:
使用扩展运算符,可以将上面的内容重写为:
Math.max(...[10, 20]); // 20Math.max(...[-10, -20]); // -10Math.max(...[-10, 20]); // 20
When calling a function using the variadic operator, you can even add additional values, e.g.
当使用变量运算符调用函数时,您甚至可以添加额外的值。
Math.max(...[10, 20], 50); // 50Math.max(...[-10, -20], 50); // 50
Bonus:
奖金:
Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push
, splice
, etc.
在ES5中,您需要使用push、splice等组合返回到命令式代码中,扩展操作符允许您使用数组文字语法来创建新的数组。
let foo = ['b', 'c'];let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
#8
20
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)
从这里推进(约翰·雷切克)
#9
15
Others have already given some solutions in which they augment Array.prototype
. All I want in this answer is to clarify whether it should be Math.min.apply( Math, array )
or Math.min.apply( null, array )
. So what context should be used, Math
or null
?
有些人已经给出了一些增强Array.prototype的解决方案。在这个答案中,我想要澄清的是,它是否应该是Math.min。应用(数学,数组)或Math.min。应用(null,数组)。那么应该使用什么上下文,Math还是null?
When passing null
as a context to apply
, then the context will default to the global object (the window
object in the case of browsers). Passing the Math
object as the context would be the correct solution, but it won't hurt passing null
either. Here's an example when null
might cause trouble, when decorating the Math.max
function:
当将null传递给要应用的上下文时,上下文将默认为全局对象(在浏览器中是窗口对象)。将Math对象作为上下文传递是正确的解决方案,但是传递null也不会有什么影响。这里有一个例子,当修饰数学时,null可能会引起麻烦。max函数:
// decorate Math.max(function (oldMax) { Math.max = function () { this.foo(); // call Math.foo, or at least that's what we want return oldMax.apply(this, arguments); };})(Math.max);Math.foo = function () { print("foo");};Array.prototype.max = function() { return Math.max.apply(null, this); // <-- passing null as the context};var max = [1, 2, 3].max();print(max);
The above will throw an exception because this.foo
will be evaluated as window.foo
, which is undefined
. If we replace null
with Math
, things will work as expected and the string "foo" will be printed to the screen (I tested this using Mozilla Rhino).
上面的代码会抛出一个异常,因为这一点。foo将被计算为窗口。喷火,这是未定义的。如果我们用Math替换null,事情就会按照预期的那样工作,字符串“foo”将被打印到屏幕上(我使用Mozilla Rhino对它进行了测试)。
You can pretty much assume that nobody has decorated Math.max
so, passing null
will work without problems.
你几乎可以假设没有人修过数学。因此,传递null将不会产生任何问题。
#10
14
One more way to do it:
还有一种方法:
var arrayMax = Function.prototype.apply.bind(Math.max, null);
Usage:
用法:
var max = arrayMax([2, 5, 1]);
#11
13
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max
function getMaxOfArray(numArray) { return Math.max.apply(null, numArray);}var arr = [100, 0, 50];console.log(getMaxOfArray(arr))
this worked for me.
这为我工作。
#12
11
I am surprised not one mentiond the reduce function.
我对简化函数没有提到感到惊讶。
var arr = [1, 10, 5, 11, 2]var b = arr.reduce(function(previous,current){ return previous > current ? previous:current });b => 11arr => [1, 10, 5, 11, 2]
#13
9
For big arrays (~10⁷ elements), Math.min
and Math.max
procuces a RangeError (Maximum call stack size exceeded) in node.js.
对大型数组(~ 10⁷元素),数学。最小值和数学。max在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;};
#14
9
A simple solution to find the minimum value over an Array
of elements is to use the Array
prototype function reduce
:
一个简单的解决方法是使用数组原型函数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):
或者使用JavaScript内置的Math.Min()函数(感谢@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.
这把min设置为[0],然后检查A[1]…A[n]是否严格小于当前最小值,如果A[i] < min,则通过返回这个值将min更新为A[i]。
#15
8
This may suit your purposes.
这可能符合你的目的。
Array.prototype.min = function(comparer) { if (this.length === 0) return null; if (this.length === 1) return this[0]; comparer = (comparer || Math.min); var v = this[0]; for (var i = 1; i < this.length; i++) { v = comparer(this[i], v); } return v;}Array.prototype.max = function(comparer) { if (this.length === 0) return null; if (this.length === 1) return this[0]; comparer = (comparer || Math.max); var v = this[0]; for (var i = 1; i < this.length; i++) { v = comparer(this[i], v); } return v;}
#16
8
I had the same problem, I needed to obtain the minimum and maximum values of an array and, to my surprise, there were no built-in functions for arrays. After reading a lot, I decided to test the "top 3" solutions myself:
我遇到了同样的问题,我需要获得一个数组的最小值和最大值,令我惊讶的是,数组没有内置函数。在阅读了很多之后,我决定亲自测试“前三种”解决方案:
- discrete solution: a FOR loop to check every element of the array against the current max and/or min value;
- 离散解:一个FOR循环,根据当前的最大值和/或最小值检查数组的每个元素;
- APPLY solution: sending the array to the Math.max and/or Math.min internal functions using apply(null,array);
- 应用解决方案:将数组发送给数学。马克斯和/或数学。最小内部函数使用apply(null,array);
- REDUCE solution: recursing a check against every element of the array using reduce(function).
- REDUCE解决方案:使用REDUCE(函数)对数组的每个元素进行递归检查。
The test code was this:
测试代码是:
function GetMaxDISCRETE(A){ var MaxX=A[0]; for (var X=0;X<A.length;X++) if (MaxX<A[X]) MaxX=A[X]; return MaxX;}function GetMaxAPPLY(A){ return Math.max.apply(null,A);}function GetMaxREDUCE(A){ return A.reduce(function(p,c) { return p>c?p:c; });}
The array A was filled with 100,000 random integer numbers, each function was executed 10,000 times on Mozilla Firefox 28.0 on an intel Pentium 4 2.99GHz desktop with Windows Vista. The times are in seconds, retrieved by performance.now() function. The results were these, with 3 fractional digits and standard deviation:
数组A中包含了100,000个随机整数,每个函数在Mozilla Firefox 28.0上执行了10,000次,在intel Pentium 4 2.99GHz的桌面和Windows Vista中。时间以秒为单位,通过性能检索。now()函数。结果为:
- Discrete solution: mean=0.161s, sd=0.078
- 离散的解决方案:意味着= 0.161 s,sd = 0.078
- APPLY solution: mean=3.571s, sd=0.487
- 应用解决方案:意味着= 3.571 s,sd = 0.487
- REDUCE solution: mean=0.350s, sd=0.044
- 减少解决方案:意味着= 0.350 s,sd = 0.044
The REDUCE solution was 117% slower than the discrete solution. The APPLY solution was the worse, 2,118% slower than the discrete solution. Besides, as Peter observed, it doesn't work for large arrays (about more than 1,000,000 elements).
减少的解决方案比离散的解决方案慢了117%。应用解决方案更糟,比离散解决方案慢了2,118%。此外,正如Peter所观察到的,它不能用于大型数组(大约超过1,000,000个元素)。
Also, to complete the tests, I tested this extended discrete code:
另外,为了完成测试,我测试了扩展的离散代码:
var MaxX=A[0],MinX=A[0];for (var X=0;X<A.length;X++){ if (MaxX<A[X]) MaxX=A[X]; if (MinX>A[X]) MinX=A[X];}
The timing: mean=0.218s, sd=0.094
时间:平均= 0.218年代,sd = 0.094
So, it is 35% slower than the simple discrete solution, but it retrieves both the maximum and the minimum values at once (any other solution would take at least twice that to retrieve them). Once the OP needed both values, the discrete solution would be the best choice (even as two separate functions, one for calculating maximum and another for calculating minimum, they would outperform the second best, the REDUCE solution).
因此,它比简单的离散解决方案慢了35%,但是它同时检索了最大值和最小值(任何其他的解决方案至少需要两次来检索它们)。一旦OP需要这两个值,离散解将是最佳选择(即使是两个单独的函数,一个用于计算最大值,另一个用于计算最小值,它们也将优于第二个最佳,即REDUCE解)。
#17
8
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
#18
8
The following code works for me :
下面的代码适用于我:
var valueList = [10,4,17,9,3];var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });
#19
6
I thought I'd share my simple and easy to understand solution.
我想分享我简单易懂的解决方案。
For the min:
最小值:
var arr = [3, 4, 12, 1, 0, 5];var min = arr[0];for (var k = 1; k < arr.length; k++) { if (arr[k] < min) { min = arr[k]; }}console.log("Min is: " + min);
And for the max:
和马克斯:
var arr = [3, 4, 12, 1, 0, 5];var max = arr[0];for (var k = 1; k < arr.length; k++) { if (arr[k] > max) { max = arr[k]; }}console.log("Max is: " + max);
#20
5
Iterate through, keeping track as you go.
迭代,跟踪你的进程。
var min = null;var max = null;for (var i = 0, len = arr.length; i < len; ++i){ var elem = arr[i]; if (min === null || min > elem) min = elem; if (max === null || max < elem) max = elem;}alert( "min = " + min + ", max = " + max );
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.
如果数组中没有元素,这将使最小/最大值为null。如果数组中有任何元素,将在一次遍历中设置最小值和最大值。
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/
您还可以使用上面的范围方法扩展数组,以允许重用和提高可读性。参见http://jsfiddle.net/9C9fU/。
Array.prototype.range = function() { var min = null, max = null, i, len; for (i = 0, len = this.length; i < len; ++i) { var elem = this[i]; if (min === null || min > elem) min = elem; if (max === null || max < elem) max = elem; } return { min: min, max: max }};
Used as
用作
var arr = [3, 9, 22, -7, 44, 18, 7, 9, 15];var range = arr.range();console.log(range.min);console.log(range.max);
#21
5
Simple stuff, really.
简单的东西,真的。
var arr = [10,20,30,40];arr.max = function() { return Math.max.apply(Math, this); }; //attach max functarr.min = function() { return Math.min.apply(Math, this); }; //attach min functalert("min: " + arr.min() + " max: " + arr.max());
#22
5
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.
这是一种从数组中获取最大值的方法。创建一个副本(使用slice),然后按降序对副本进行排序并获取第一个项。
var myArray = [ {"ID": 1, "Cost": 200}, {"ID": 2, "Cost": 1000}, {"ID": 3, "Cost": 50}, {"ID": 4, "Cost": 500}]maxsort = myArray.slice(0).sort(function(a, b) { return b.ID - a.ID })[0].ID;
#23
5
Using Math.max()
or Math.min()
使用Math.max()或Math.min()
Math.max(10, 20); // 20Math.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 .prototype.apply()查找数值数组中的最大元素。getMaxOfArray([1,2,3])等同于数学。max(1,2,3),但是您可以在任何大小的编程构造数组中使用getMaxOfArray()。
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); // 3var min = Math.min(...arr); // 1
#24
4
ChaosPandion's solution works if you're using protoype. If not, consider this:
如果你正在使用protoype,那么ChaosPandion的解决方案是有效的。如果没有,考虑一下:
Array.max = function( array ){ return Math.max.apply( Math, array );};Array.min = function( array ){ return Math.min.apply( Math, array );};
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.
如果数组值不是整数,上面的函数将返回NaN,因此应该构建一些功能来避免这种情况。否则这将工作。
#25
3
If you are using prototype.js framework, then this code will work ok:
如果你正在使用原型。js框架,那么这个代码就可以工作了:
arr.min();arr.max();
Documented here: Javascript prototype framework for max
这里有文档:max的Javascript原型框架
#26
3
If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.
如果你用图书馆的糖。你可以像你建议的那样写arr.min()和arr.max()。您还可以从非数字数组中获得最小值和最大值。
min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.
min(map, all = false)以最低的值返回数组中的元素。映射可能是一个函数,映射到要检查的值或作为快捷方式的字符串。如果全部为真,将返回数组中的所有min值。
max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.
max(map, all = false)返回数组中值最大的元素。映射可能是一个函数,映射到要检查的值或作为快捷方式的字符串。如果一切为真,将返回数组中的所有最大值。
Examples:
例子:
[1,2,3].min() == 1['fee','fo','fum'].min('length') == "fo"['fee','fo','fum'].min('length', true) == ["fo"]['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"[{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}['fee','fo','fum'].max('length', true) == ["fee","fum"]
Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:
库如Lo-Dash和下划线。js还提供了类似的功能强大的min和max:
Example from Lo-Dash:
从Lo-Dash示例:
_.max([4, 2, 8, 6]) == 8var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }];_.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }
#27
2
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; }}
#28
2
Two ways are shorter and easy:
有两种方法既简单又快捷:
let arr = [2, 6, 1, 0]// Way 1:console.log('Max val = ', Math.max.apply(null, arr))//Way 2:let max = arr.reduce(function(a, b) { return Math.max(a, b);});
#29
1
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?
我喜欢Linus的reduce()方法,特别是对于大型数组。但是,只要您知道您同时需要min和max,为什么要迭代两次?
Array.prototype.minmax = function () { return this.reduce(function (p, v) { return [(p[0] < v ? p[0] : v), (p[1] > v ? p[1] : v)]; }, [this[0], this[0]]);}
Of course, if you prefer the iterative approach, you can do that too:
当然,如果您喜欢迭代方法,您也可以这样做:
Array.prototype.minmax = function () { var mn = this[0], mx = this[0]; this.forEach(function (v) { if (v < mn) mn = v; if (v > mx) mx = v; }); return [mn, mx];};
#30
1
create a simple object
创建一个简单的对象
var myArray = new Array();myArray = [10,12,14,100];var getMaxHeight = { hight : function( array ){ return Math.max.apply( Math, array );}getMaxHeight.hight(myArray);
#1
667
How about augmenting the built-in Array object to use Math.max
/Math.min
instead:
如何扩展内置数组对象以使用Math.max/Math。最小值:
Array.prototype.max = function() { return Math.max.apply(null, this);};Array.prototype.min = function() { return Math.min.apply(null, this);};
Here is a JSFiddle.
这是一个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:
增加内嵌项可能会导致与其他库的冲突(有人看到),因此您可以更轻松地直接将'ing Math.xxx()应用到您的数组中:
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:
或者,假设您的浏览器支持ECMAScript 6,您可以使用与apply方法类似的扩展操作符:
var min = Math.min( ...arr ), max = Math.max( ...arr );
#2
303
var max_of_array = Math.max.apply(Math, array);
For a full discussion see:http://aaroncrane.co.uk/2008/11/javascript_max_api/
详细讨论请参见:http://aaroncrane.co.uk/2008/11/javascript_max_api/
#3
136
For big arrays (~10⁷ elements), Math.min
and Math.max
both produces the following error in Node.js.
对大型数组(~ 10⁷元素),数学。最小值和数学。max在Node.js中都会产生以下错误。
RangeError: Maximum call stack size exceeded
RangeError:超出最大调用堆栈大小
A more robust solution is to not add every element to the call stack, but to instead pass an array:
一个更可靠的解决方案是不向调用堆栈添加所有元素,而是传递一个数组:
function arrayMin(arr) { return arr.reduce(function (p, v) { return ( p < v ? p : v ); });}function arrayMax(arr) { return arr.reduce(function (p, v) { return ( p > v ? p : v ); });}
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.
如果您关心速度,下面的代码比Math.max快大约3倍。申请在我的电脑上。见http://jsperf.com/min-and-max-in-array/2。
function arrayMin(arr) { var len = arr.length, min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min;};function arrayMax(arr) { var len = arr.length, max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max;};
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.
如果数组包含字符串而不是数字,还需要将它们强制化为数字。下面的代码可以做到这一点,但是在我的机器上,它会使代码慢下来大约10倍。见http://jsperf.com/min-and-max-in-array/3。
function arrayMin(arr) { var len = arr.length, min = Infinity; while (len--) { if (Number(arr[len]) < min) { min = Number(arr[len]); } } return min;};function arrayMax(arr) { var len = arr.length, max = -Infinity; while (len--) { if (Number(arr[len]) > max) { max = Number(arr[len]); } } return max;};
#4
84
Using spread operator (ES6)
使用扩散算子(ES6)
Math.max(...array); // the same with "min" => Math.min(...array);
const array = [10, 2, 33, 4, 5];console.log( Math.max(...array))
#5
49
If you're paranoid like me about using Math.max.apply
(which could cause errors when given large arrays according to MDN), try this:
如果你像我一样偏执地想用数学。apply(根据MDN给定大数组时可能会导致错误),尝试以下方法:
function arrayMax(array) { return array.reduce(function(a, b) { return Math.max(a, b); });}function arrayMin(array) { return array.reduce(function(a, b) { return Math.min(a, b); });}
Or, in ES6:
或者,在ES6:
function arrayMax(array) { return array.reduce((a, b) => Math.max(a, b));}function arrayMin(array) { return array.reduce((a, b) => Math.min(a, b));}
The anonymous functions are unfortunately necessary (instead of using Math.max.bind(Math)
because reduce
doesn't just pass a
and b
to its function, but also i
and a reference to the array itself, so we have to ensure we don't try to call max
on those as well.
不幸的是,匿名函数是必需的(而不是使用Math.max.bind(Math),因为reduce不仅将a和b传递给它的函数,而且还将i和一个对数组本身的引用传递给它,所以我们必须确保不会对它们调用max。
#6
42
tl;dr
var max = Math.max(...arrayOfNumbers);
Official Math.max()
MDN documentation
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.下面的函数使用function .prototype.apply()查找数值数组中的最大元素。getMaxOfArray([1,2,3])等同于数学。max(1,2,3),但是您可以在任何大小的编程构造数组中使用getMaxOfArray()。
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);
#7
34
.apply
is often used when the intention is to invoke a variadic function with a list of argument values, e.g.
.apply通常用于调用一个包含一系列参数值的变量函数,例如:
The Math.max([value1[,value2, ...]])
function returns the largest of zero or more numbers.
的数学。函数的作用是:返回0个或多个数字中最大的一个。
Math.max(10, 20); // 20Math.max(-10, -20); // -10Math.max(-10, 20); // 20
The Math.max()
method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.
max()方法不允许您传入数组。如果您有一个需要最大值的列表,您通常会使用function .prototype.apply()调用这个函数。
Math.max.apply(null, [10, 20]); // 20Math.max.apply(null, [-10, -20]); // -10Math.max.apply(null, [-10, 20]); // 20
However, as of the ECMAScript 6 you can use the spread operator:
但是,从ECMAScript 6开始,您可以使用扩展操作符:
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
扩展运算符允许在需要多个参数(用于函数调用)或多个元素(用于数组文本)的地方扩展表达式。
Using the spread operator, the above can be rewritten as such:
使用扩展运算符,可以将上面的内容重写为:
Math.max(...[10, 20]); // 20Math.max(...[-10, -20]); // -10Math.max(...[-10, 20]); // 20
When calling a function using the variadic operator, you can even add additional values, e.g.
当使用变量运算符调用函数时,您甚至可以添加额外的值。
Math.max(...[10, 20], 50); // 50Math.max(...[-10, -20], 50); // 50
Bonus:
奖金:
Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push
, splice
, etc.
在ES5中,您需要使用push、splice等组合返回到命令式代码中,扩展操作符允许您使用数组文字语法来创建新的数组。
let foo = ['b', 'c'];let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
#8
20
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)
从这里推进(约翰·雷切克)
#9
15
Others have already given some solutions in which they augment Array.prototype
. All I want in this answer is to clarify whether it should be Math.min.apply( Math, array )
or Math.min.apply( null, array )
. So what context should be used, Math
or null
?
有些人已经给出了一些增强Array.prototype的解决方案。在这个答案中,我想要澄清的是,它是否应该是Math.min。应用(数学,数组)或Math.min。应用(null,数组)。那么应该使用什么上下文,Math还是null?
When passing null
as a context to apply
, then the context will default to the global object (the window
object in the case of browsers). Passing the Math
object as the context would be the correct solution, but it won't hurt passing null
either. Here's an example when null
might cause trouble, when decorating the Math.max
function:
当将null传递给要应用的上下文时,上下文将默认为全局对象(在浏览器中是窗口对象)。将Math对象作为上下文传递是正确的解决方案,但是传递null也不会有什么影响。这里有一个例子,当修饰数学时,null可能会引起麻烦。max函数:
// decorate Math.max(function (oldMax) { Math.max = function () { this.foo(); // call Math.foo, or at least that's what we want return oldMax.apply(this, arguments); };})(Math.max);Math.foo = function () { print("foo");};Array.prototype.max = function() { return Math.max.apply(null, this); // <-- passing null as the context};var max = [1, 2, 3].max();print(max);
The above will throw an exception because this.foo
will be evaluated as window.foo
, which is undefined
. If we replace null
with Math
, things will work as expected and the string "foo" will be printed to the screen (I tested this using Mozilla Rhino).
上面的代码会抛出一个异常,因为这一点。foo将被计算为窗口。喷火,这是未定义的。如果我们用Math替换null,事情就会按照预期的那样工作,字符串“foo”将被打印到屏幕上(我使用Mozilla Rhino对它进行了测试)。
You can pretty much assume that nobody has decorated Math.max
so, passing null
will work without problems.
你几乎可以假设没有人修过数学。因此,传递null将不会产生任何问题。
#10
14
One more way to do it:
还有一种方法:
var arrayMax = Function.prototype.apply.bind(Math.max, null);
Usage:
用法:
var max = arrayMax([2, 5, 1]);
#11
13
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/max
function getMaxOfArray(numArray) { return Math.max.apply(null, numArray);}var arr = [100, 0, 50];console.log(getMaxOfArray(arr))
this worked for me.
这为我工作。
#12
11
I am surprised not one mentiond the reduce function.
我对简化函数没有提到感到惊讶。
var arr = [1, 10, 5, 11, 2]var b = arr.reduce(function(previous,current){ return previous > current ? previous:current });b => 11arr => [1, 10, 5, 11, 2]
#13
9
For big arrays (~10⁷ elements), Math.min
and Math.max
procuces a RangeError (Maximum call stack size exceeded) in node.js.
对大型数组(~ 10⁷元素),数学。最小值和数学。max在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;};
#14
9
A simple solution to find the minimum value over an Array
of elements is to use the Array
prototype function reduce
:
一个简单的解决方法是使用数组原型函数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):
或者使用JavaScript内置的Math.Min()函数(感谢@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.
这把min设置为[0],然后检查A[1]…A[n]是否严格小于当前最小值,如果A[i] < min,则通过返回这个值将min更新为A[i]。
#15
8
This may suit your purposes.
这可能符合你的目的。
Array.prototype.min = function(comparer) { if (this.length === 0) return null; if (this.length === 1) return this[0]; comparer = (comparer || Math.min); var v = this[0]; for (var i = 1; i < this.length; i++) { v = comparer(this[i], v); } return v;}Array.prototype.max = function(comparer) { if (this.length === 0) return null; if (this.length === 1) return this[0]; comparer = (comparer || Math.max); var v = this[0]; for (var i = 1; i < this.length; i++) { v = comparer(this[i], v); } return v;}
#16
8
I had the same problem, I needed to obtain the minimum and maximum values of an array and, to my surprise, there were no built-in functions for arrays. After reading a lot, I decided to test the "top 3" solutions myself:
我遇到了同样的问题,我需要获得一个数组的最小值和最大值,令我惊讶的是,数组没有内置函数。在阅读了很多之后,我决定亲自测试“前三种”解决方案:
- discrete solution: a FOR loop to check every element of the array against the current max and/or min value;
- 离散解:一个FOR循环,根据当前的最大值和/或最小值检查数组的每个元素;
- APPLY solution: sending the array to the Math.max and/or Math.min internal functions using apply(null,array);
- 应用解决方案:将数组发送给数学。马克斯和/或数学。最小内部函数使用apply(null,array);
- REDUCE solution: recursing a check against every element of the array using reduce(function).
- REDUCE解决方案:使用REDUCE(函数)对数组的每个元素进行递归检查。
The test code was this:
测试代码是:
function GetMaxDISCRETE(A){ var MaxX=A[0]; for (var X=0;X<A.length;X++) if (MaxX<A[X]) MaxX=A[X]; return MaxX;}function GetMaxAPPLY(A){ return Math.max.apply(null,A);}function GetMaxREDUCE(A){ return A.reduce(function(p,c) { return p>c?p:c; });}
The array A was filled with 100,000 random integer numbers, each function was executed 10,000 times on Mozilla Firefox 28.0 on an intel Pentium 4 2.99GHz desktop with Windows Vista. The times are in seconds, retrieved by performance.now() function. The results were these, with 3 fractional digits and standard deviation:
数组A中包含了100,000个随机整数,每个函数在Mozilla Firefox 28.0上执行了10,000次,在intel Pentium 4 2.99GHz的桌面和Windows Vista中。时间以秒为单位,通过性能检索。now()函数。结果为:
- Discrete solution: mean=0.161s, sd=0.078
- 离散的解决方案:意味着= 0.161 s,sd = 0.078
- APPLY solution: mean=3.571s, sd=0.487
- 应用解决方案:意味着= 3.571 s,sd = 0.487
- REDUCE solution: mean=0.350s, sd=0.044
- 减少解决方案:意味着= 0.350 s,sd = 0.044
The REDUCE solution was 117% slower than the discrete solution. The APPLY solution was the worse, 2,118% slower than the discrete solution. Besides, as Peter observed, it doesn't work for large arrays (about more than 1,000,000 elements).
减少的解决方案比离散的解决方案慢了117%。应用解决方案更糟,比离散解决方案慢了2,118%。此外,正如Peter所观察到的,它不能用于大型数组(大约超过1,000,000个元素)。
Also, to complete the tests, I tested this extended discrete code:
另外,为了完成测试,我测试了扩展的离散代码:
var MaxX=A[0],MinX=A[0];for (var X=0;X<A.length;X++){ if (MaxX<A[X]) MaxX=A[X]; if (MinX>A[X]) MinX=A[X];}
The timing: mean=0.218s, sd=0.094
时间:平均= 0.218年代,sd = 0.094
So, it is 35% slower than the simple discrete solution, but it retrieves both the maximum and the minimum values at once (any other solution would take at least twice that to retrieve them). Once the OP needed both values, the discrete solution would be the best choice (even as two separate functions, one for calculating maximum and another for calculating minimum, they would outperform the second best, the REDUCE solution).
因此,它比简单的离散解决方案慢了35%,但是它同时检索了最大值和最小值(任何其他的解决方案至少需要两次来检索它们)。一旦OP需要这两个值,离散解将是最佳选择(即使是两个单独的函数,一个用于计算最大值,另一个用于计算最小值,它们也将优于第二个最佳,即REDUCE解)。
#17
8
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
#18
8
The following code works for me :
下面的代码适用于我:
var valueList = [10,4,17,9,3];var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });
#19
6
I thought I'd share my simple and easy to understand solution.
我想分享我简单易懂的解决方案。
For the min:
最小值:
var arr = [3, 4, 12, 1, 0, 5];var min = arr[0];for (var k = 1; k < arr.length; k++) { if (arr[k] < min) { min = arr[k]; }}console.log("Min is: " + min);
And for the max:
和马克斯:
var arr = [3, 4, 12, 1, 0, 5];var max = arr[0];for (var k = 1; k < arr.length; k++) { if (arr[k] > max) { max = arr[k]; }}console.log("Max is: " + max);
#20
5
Iterate through, keeping track as you go.
迭代,跟踪你的进程。
var min = null;var max = null;for (var i = 0, len = arr.length; i < len; ++i){ var elem = arr[i]; if (min === null || min > elem) min = elem; if (max === null || max < elem) max = elem;}alert( "min = " + min + ", max = " + max );
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.
如果数组中没有元素,这将使最小/最大值为null。如果数组中有任何元素,将在一次遍历中设置最小值和最大值。
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/
您还可以使用上面的范围方法扩展数组,以允许重用和提高可读性。参见http://jsfiddle.net/9C9fU/。
Array.prototype.range = function() { var min = null, max = null, i, len; for (i = 0, len = this.length; i < len; ++i) { var elem = this[i]; if (min === null || min > elem) min = elem; if (max === null || max < elem) max = elem; } return { min: min, max: max }};
Used as
用作
var arr = [3, 9, 22, -7, 44, 18, 7, 9, 15];var range = arr.range();console.log(range.min);console.log(range.max);
#21
5
Simple stuff, really.
简单的东西,真的。
var arr = [10,20,30,40];arr.max = function() { return Math.max.apply(Math, this); }; //attach max functarr.min = function() { return Math.min.apply(Math, this); }; //attach min functalert("min: " + arr.min() + " max: " + arr.max());
#22
5
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.
这是一种从数组中获取最大值的方法。创建一个副本(使用slice),然后按降序对副本进行排序并获取第一个项。
var myArray = [ {"ID": 1, "Cost": 200}, {"ID": 2, "Cost": 1000}, {"ID": 3, "Cost": 50}, {"ID": 4, "Cost": 500}]maxsort = myArray.slice(0).sort(function(a, b) { return b.ID - a.ID })[0].ID;
#23
5
Using Math.max()
or Math.min()
使用Math.max()或Math.min()
Math.max(10, 20); // 20Math.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 .prototype.apply()查找数值数组中的最大元素。getMaxOfArray([1,2,3])等同于数学。max(1,2,3),但是您可以在任何大小的编程构造数组中使用getMaxOfArray()。
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); // 3var min = Math.min(...arr); // 1
#24
4
ChaosPandion's solution works if you're using protoype. If not, consider this:
如果你正在使用protoype,那么ChaosPandion的解决方案是有效的。如果没有,考虑一下:
Array.max = function( array ){ return Math.max.apply( Math, array );};Array.min = function( array ){ return Math.min.apply( Math, array );};
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.
如果数组值不是整数,上面的函数将返回NaN,因此应该构建一些功能来避免这种情况。否则这将工作。
#25
3
If you are using prototype.js framework, then this code will work ok:
如果你正在使用原型。js框架,那么这个代码就可以工作了:
arr.min();arr.max();
Documented here: Javascript prototype framework for max
这里有文档:max的Javascript原型框架
#26
3
If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.
如果你用图书馆的糖。你可以像你建议的那样写arr.min()和arr.max()。您还可以从非数字数组中获得最小值和最大值。
min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.
min(map, all = false)以最低的值返回数组中的元素。映射可能是一个函数,映射到要检查的值或作为快捷方式的字符串。如果全部为真,将返回数组中的所有min值。
max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.
max(map, all = false)返回数组中值最大的元素。映射可能是一个函数,映射到要检查的值或作为快捷方式的字符串。如果一切为真,将返回数组中的所有最大值。
Examples:
例子:
[1,2,3].min() == 1['fee','fo','fum'].min('length') == "fo"['fee','fo','fum'].min('length', true) == ["fo"]['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"[{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}['fee','fo','fum'].max('length', true) == ["fee","fum"]
Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:
库如Lo-Dash和下划线。js还提供了类似的功能强大的min和max:
Example from Lo-Dash:
从Lo-Dash示例:
_.max([4, 2, 8, 6]) == 8var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }];_.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }
#27
2
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; }}
#28
2
Two ways are shorter and easy:
有两种方法既简单又快捷:
let arr = [2, 6, 1, 0]// Way 1:console.log('Max val = ', Math.max.apply(null, arr))//Way 2:let max = arr.reduce(function(a, b) { return Math.max(a, b);});
#29
1
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?
我喜欢Linus的reduce()方法,特别是对于大型数组。但是,只要您知道您同时需要min和max,为什么要迭代两次?
Array.prototype.minmax = function () { return this.reduce(function (p, v) { return [(p[0] < v ? p[0] : v), (p[1] > v ? p[1] : v)]; }, [this[0], this[0]]);}
Of course, if you prefer the iterative approach, you can do that too:
当然,如果您喜欢迭代方法,您也可以这样做:
Array.prototype.minmax = function () { var mn = this[0], mx = this[0]; this.forEach(function (v) { if (v < mn) mn = v; if (v > mx) mx = v; }); return [mn, mx];};
#30
1
create a simple object
创建一个简单的对象
var myArray = new Array();myArray = [10,12,14,100];var getMaxHeight = { hight : function( array ){ return Math.max.apply( Math, array );}getMaxHeight.hight(myArray);