Javascript:使用reduce() 查找最小值和最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43576241/
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
Javascript: Using reduce() to find min and max values?
提问by Alyssa June
I have this code for a class where I'm supposed to use the reduce() method to find the min and max values in an array. However, we are required to use only a single call to reduce. The return array should be of size 2, but I know that the reduce() method always returns an array of size 1. I'm able to obtain the minimum value using the code below, however I don't know how to obtain the max value in that same call. I assume that once I do obtain the max value that I just push it to the array after the reduce() method finishes.
我有一个类的代码,我应该在其中使用 reduce() 方法来查找数组中的最小值和最大值。但是,我们只需要使用一个调用来减少。返回数组的大小应为 2,但我知道 reduce() 方法总是返回大小为 1 的数组。我可以使用下面的代码获取最小值,但是我不知道如何获取同一个调用中的最大值。我假设一旦我获得了最大值,我就在 reduce() 方法完成后将其推送到数组中。
/**
* Takes an array of numbers and returns an array of size 2,
* where the first element is the smallest element in items,
* and the second element is the largest element in items.
*
* Must do this by using a single call to reduce.
*
* For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]
*/
function minMax(items) {
var minMaxArray = items.reduce(
(accumulator, currentValue) => {
return (accumulator < currentValue ? accumulator : currentValue);
}
);
return minMaxArray;
}
采纳答案by colxi
The trick consist in provide an empty Array as initialValue Parameter
诀窍在于提供一个空数组作为初始值参数
arr.reduce(callback, [initialValue])
initialValue [Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
initialValue [可选] 用作回调第一次调用的第一个参数的值。如果未提供初始值,则将使用数组中的第一个元素。
So the code would look like this:
所以代码看起来像这样:
function minMax(items) {
return items.reduce((acc, val) => {
acc[0] = ( acc[0] === undefined || val < acc[0] ) ? val : acc[0]
acc[1] = ( acc[1] === undefined || val > acc[1] ) ? val : acc[1]
return acc;
}, []);
}
回答by Sergey Zhukov
In ES6you can use spread operator. One string solution:
在ES6 中,您可以使用扩展运算符。一串解决方案:
Math.min(...items)
回答by Ilyas Kabirov
You can use array as return value:
您可以使用数组作为返回值:
function minMax(items) {
return items.reduce(
(accumulator, currentValue) => {
return [
Math.min(currentValue, accumulator[0]),
Math.max(currentValue, accumulator[1])
];
}, [Number.MAX_VALUE, Number.MIN_VALUE]
);
}
回答by adeneo
As the reduce call isn't really needed at all, you could have some fun with it
由于根本不需要reduce调用,您可以从中获得一些乐趣
let items = [62, 3, 7, 9, 33, 6, 322, 67, 853];
let arr = items.reduce((w,o,r,k,s=Math)=>[s.min.apply(0, k),s.max.apply(0, k)],[]);
console.log(arr);
All you'd really need is let minMaxArray = [Math.min.apply(0,items), Math.max.apply(0,items)]
你真正需要的是 let minMaxArray = [Math.min.apply(0,items), Math.max.apply(0,items)]
回答by RomanPerekhrest
The solution using Math.min()and Math.max()functions:
解决方案使用Math.min()和Math.max()功能:
function minMax(items) {
var minMaxArray = items.reduce(function (r, n) {
r[0] = (!r[0])? n : Math.min(r[0], n);
r[1] = (!r[1])? n : Math.max(r[1], n);
return r;
}, []);
return minMaxArray;
}
console.log(minMax([4, 1, 2, 7, 6]));
回答by Yauheni Charniauski
const values = [1,2,3,4,5];
const [first] = values;
const maxValue = values.reduce((acc, value) => Math.max(acc, value), first);
回答by Ahmed Mahmoud
To get min and max value of an array using reduce function
使用reduce函数获取数组的最小值和最大值
const ArrayList = [1, 2, 3, 4, 3, 20, 0];
const LargestNum = ArrayList.reduce((prev, curr) => {
return Math.max(prev, curr)
});
const MinNum = ArrayList.reduce((prev,curr)=>{
return Math.min(pre,curr)
});
console.log(LargestNum);
console.log(MinNum);
回答by tobias
1. Solution using only Math.minand Math.max:
1. 仅使用Math.min和 的解决方案Math.max:
??
This will not work if you use big arrays, i.e. supply Math.min()with many arguments as "you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception."from MDN web docs.
?? 如果您使用大数组,即提供Math.min()许多参数,这将不起作用,因为“您冒着超过 JavaScript 引擎的参数长度限制的风险。应用参数过多的函数的后果(想想超过数万个参数)因引擎而异(JavaScriptCore 的硬编码参数限制为 65536),因为该限制(甚至任何过大堆栈行为的性质)是未指定的。某些引擎会抛出异常。” 来自 MDN 网络文档。
function minMax(items) {
return [
Math.min.apply(null, items),
Math.max.apply(null, items)
]
}
... or if you prefer ES6's Spread syntax:
...或者如果您更喜欢ES6 的 Spread 语法:
const minMax = items => [
Math.min(...items),
Math.max(...items)
]
2. Solution using Array.prototype.reduce, Math.minand Math.max
2. 解决方案使用Array.prototype.reduce,Math.min和Math.max
function minMax(arr) {
return arr.reduce(function(acc, cur) {
return [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
]
}, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
}
... or shortened:
...或缩短:
const minMax = items =>
items.reduce((acc, cur) =>
[Math.min(cur, acc[0]), Math.max(cur, acc[1])],
[Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]
)
3. Solution including sensible validations
3. 包括合理验证在内的解决方案
function minMax(items) {
let newItems = []
const isArray = Array.isArray(items)
const onlyHasNumbers = !items.some(i => isNaN(parseFloat(i)))
// only proceed if items is a non-empty array of numbers
if (isArray && items.length > 0 && onlyHasNumbers) {
newItems = items.reduce(function(acc, cur) {
return [
Math.min(cur, acc[0]),
Math.max(cur, acc[1])
]
}, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])
}
return newItems
}
Documentation for Math.min
Documentation for Math.max
Documentation for Array.prototype.reduce()
回答by SlimeSli
let arr = [8978, 'lol', -78, 989, NaN, null, undefined, 6, 9, 55, 989];
let minMax = arr.reduce(([min, max], v) => [
Math.min(min, v) || min,
Math.max(max, v) || max], [Infinity, -Infinity]);
console.log(minMax);
How it works:
这个怎么运作:
|| mincheck isvnumber.[Infinity, -Infinity]is.reduceinitial valueIt use js destructuringassignment
|| min支票是v号码。[Infinity, -Infinity]是.reduce初始值它使用js解构赋值
回答by jusopi
I know this has been answered but I went off of @Sergey Zhukov's answer (which seems incomplete) and was able to get the min and max values in 2 lines:
我知道这已经得到了回答,但我离开了@Sergey Zhukov 的回答(这似乎不完整)并且能够在 2 行中获得最小值和最大值:
let vals = [ numeric values ]
let min = Math.min.apply(undefined, vals)
let max = Math.max.apply(undefined, vals)
I do see the value in Array.reduce, but with such a super simple use case, andso long as you understand what Function.applydoes, this would be my goto solution.
我看到的价值Array.reduce,但这样一个超级简单的用例,并且只要你明白什么Function.apply呢,这将是我转到解决方案。

