Javascript 在Javascript中从数组中获取最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8934877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Obtain smallest value from array in Javascript?
提问by lisovaccaro
Array justPrices has values such as:
数组 justPrices 具有如下值:
[0] = 1.5
[1] = 4.5
[2] = 9.9.
How do I return the smallest value in the array?
如何返回数组中的最小值?
回答by Darin Dimitrov
Jon Resig illustrated in this articlehow this could be achieved by extending the Array prototype and invoking the underlying Math.minmethod which unfortunately doesn't take an array but a variable number of arguments:
Jon Resig 在本文中说明了如何通过扩展 Array 原型并调用底层Math.min方法来实现这一点,不幸的是,该方法不接受数组而是可变数量的参数:
Array.min = function( array ){
return Math.min.apply( Math, array );
};
and then:
进而:
var minimum = Array.min(array);
回答by zzzzBov
The tersest expressive code to find the minimum value is probably rest parameters:
找到最小值的最简洁的表达代码可能是rest 参数:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)
Rest parameters are essentially a convenient shorthand for Function.prototype.apply
when you don't need to change the function's context:
Function.prototype.apply
当您不需要更改函数的上下文时,Rest 参数本质上是一种方便的简写:
var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)
This is also a great use case for Array.prototype.reduce
:
这也是一个很好的用例Array.prototype.reduce
:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)
It may be tempting to pass Math.min
directly to reduce
, however the callback receives additional parameters:
Math.min
直接传递给可能很诱人reduce
,但是回调会接收额外的参数:
callback (accumulator, currentValue, currentIndex, array)
In this particular case it may be a bit verbose. reduce
is particularly useful when you have a collection of complex data that you want to aggregate into a single value:
在这种特殊情况下,它可能有点冗长。reduce
当您有一组复杂的数据要聚合为单个值时,这尤其有用:
const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
(acc, loc) =>
acc.distance < loc.distance
? acc
: loc
)
console.log(closest)
And of course you can always use classic iteration:
当然,您始终可以使用经典迭代:
var arr,
i,
l,
min
arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
min = Math.min(min, arr[i])
}
console.log(min)
...but even classic iteration can get a modern makeover:
...但即使是经典的迭代也可以进行现代改造:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
min = Math.min(min, value)
}
console.log(min)
回答by tdowek1
I find that the easiest way to return the smallest value of an array is to use the Spread Operator on Math.min() function.
我发现返回数组最小值的最简单方法是在 Math.min() 函数上使用扩展运算符。
return Math.min(...justPrices);
//returns 1.5 on example given
The page on MDN helps to understand it better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
MDN 上的页面有助于更好地理解它:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
A little extra: This also works on Math.max() function
一点额外:这也适用于 Math.max() 函数
return Math.max(...justPrices); //returns 9.9 on example given.
返回 Math.max(...justPrices); //在给定的示例中返回 9.9。
Hope this helps!
希望这可以帮助!
回答by c69
Update:use Darin's / John Resig answer, just keep in mind that you dont need to specifiy thisArg for min
, so Math.min.apply(null, arr)
will work just fine.
更新:使用 Darin 的 / John Resig 答案,请记住,您不需要为 指定 thisArg min
,因此Math.min.apply(null, arr)
可以正常工作。
or you can just sortthe array and get value #1:
[2,6,7,4,1].sort()[0]
或者您可以对数组进行排序并获得值 #1:
[2,6,7,4,1].sort()[0]
[!] But without supplying custom number sorting function, this will only work in one, very limited case: positive numbers less than 10. See how it would break:
[!] 但是如果不提供自定义数字排序功能,这只适用于一种非常有限的情况:小于 10 的正数。看看它会如何破裂:
var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];
// correct:
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]
// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]
And, also, array is changed in-place, which might not be what you want.
而且,array 就地更改,这可能不是您想要的。
回答by Alireza
Imagine you have this array:
想象一下你有这个数组:
var arr = [1, 2, 3];
ES6 way:
ES6方式:
var min = Math.min(...arr); //min=1
ES5 way:
ES5方式:
var min = Math.min.apply(null, arr); //min=1
If you using D3.js, there is a handy function which does the same, but will ignore undefinedvalues and also check the natural order:
如果您使用 D3.js,有一个方便的函数可以执行相同的操作,但会忽略未定义的值并检查自然顺序:
d3.max(array[, accessor])
Returns the maximum value in the given array using natural order. If the array is empty, returns undefined. An optional accessor function may be specified, which is equivalent to calling array.map(accessor) before computing the maximum value.
Unlike the built-in Math.max, this method ignores undefined values; this is useful for ignoring missing data. In addition, elements are compared using natural order rather than numeric order. For example, the maximum of the strings [“20”, “3”] is “3”, while the maximum of the numbers [20, 3] is 20.
d3.max(数组[,访问器])
使用自然顺序返回给定数组中的最大值。如果数组为空,则返回 undefined。可以指定一个可选的访问器函数,相当于在计算最大值之前调用 array.map(accessor)。
与内置的 Math.max 不同,此方法忽略未定义的值;这对于忽略丢失的数据很有用。此外,元素使用自然顺序而不是数字顺序进行比较。例如,字符串 [“20”, “3”] 的最大值为“3”,而数字 [20, 3] 的最大值为 20。
And this is the source code for D3 v4:
这是 D3 v4 的源代码:
export default function(values, valueof) {
var n = values.length,
i = -1,
value,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && value > max) {
max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && value > max) {
max = value;
}
}
}
}
}
return max;
}
回答by Aaron Joel Kison
ES6 is the way of the future.
ES6 是未来之路。
arr.reduce((a, b) => Math.min(a, b));
I prefer this form because it's easily generalized for other use cases
我更喜欢这种形式,因为它很容易推广到其他用例
回答by suraj
var array =[2,3,1,9,8];
var minvalue = array[0];
for (var i = 0; i < array.length; i++) {
if(array[i]<minvalue)
{
minvalue = array[i];
}
}
console.log(minvalue);
回答by Akexis
Possibly an easier way?
可能是更简单的方法?
Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.
假设 justPrices 在价值方面混为一谈,因此您不知道最小值在哪里。
justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5
Use sort.
使用排序。
justPrices.sort();
It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.
然后它会为你安排好它们。(也可以按字母顺序排列。)然后数组将按升序排列。
justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9
You can then easily grab by the first index.
然后,您可以轻松抓取第一个索引。
justPrices[0]
I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp
我发现这比上面提出的更有用,因为如果您需要最低的 3 个数字作为示例怎么办?您还可以切换它们的排列顺序,更多信息请访问http://www.w3schools.com/jsref/jsref_sort.asp
回答by Libu Mathew
function smallest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.min.apply( Math, arguments );
}
function largest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.max.apply( Math, arguments );
}
var min = smallest(10, 11, 12, 13);
var max = largest([10, 11, 12, 13]);
console.log("Smallest: "+ min +", Largest: "+ max);
回答by svarog
If you are using Underscore or Lodash you can get the minimal value using this kind of simple functional pipeline
如果您使用 Underscore 或 Lodash,您可以使用这种简单的功能管道获得最小值
_.chain([7, 6, -1, 3, 2]).sortBy().first().value()
// -1
You also have the .min
function
你也有这个.min
功能
_.min([7, 6, -1, 3, 2])
// -1