【发布时间】:2017-09-20 10:27:17
【问题描述】:
我有一个类的代码,我应该使用 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;
}
【问题讨论】:
-
您似乎忘了实际提出问题。请查看How to Ask。
-
but I know that the reduce() method always returns an array of size 1- 这是不正确的。此外,reduce 只是一种通过回调迭代数组的方法,请考虑在minMax方法中可以在迭代器中使用的范围内的其他变量。提示:根据您的描述,您根本不必使用reduce的返回值。 -
阅读reduce() docs并更改
accumulator的initValue
标签: javascript arrays reduce