2017-04-23 326 views
5

我有一个类的代码,我应该使用reduce()方法来查找数组中的最小值和最大值。但是,我们只需要使用一个呼叫来减少。返回数组的大小应为2,但我知道reduce()方法总是返回大小为1的数组。我可以使用下面的代码获取最小值,但是我不知道如何获取在同一个呼叫中最大值。我假设一旦我确实获得了最大值,那么在reduce()方法结束之后,我将它推送到数组中。Javascript:使用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; 
} 
+0

看来您忘了实际提出问题了。请查看[问]。 – zzzzBov

+4

'但我知道reduce()方法总是返回一个大小为1的数组 - 这是不正确的。另外,reduce只是一个用回调函数迭代数组的方法,想想你可以在迭代器中使用的'minMax'方法中的其他变量。提示:根据你的描述,你不一定必须使用'reduce'的返回值。 – Adam

+0

阅读[reduce()文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control)并将'initValue'改为' accumulator' – charlietfl

回答

2

诀窍在于提供一个空的Array作为初值参数

arr.reduce(callback, [initialValue]) 

initialValue [可选]用作回调第一个调用的第一个参数的值。如果未提供初始值,则将使用阵列中的第一个元素 。

因此,代码是这样的:

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; 
    }, []); 
} 
+0

这个答案的优点是可以处理任意有序类型(例如字符串),而不仅仅是数值,这是一个很好的概括。一种可能的优化是将'initialValue'设置为'[items [0],items [0]]',这样就可以避免特殊大小写undefined,从而简化每次调用时的最小/最大计算if acc [1] = val;' – ShadowRanger

1

将溶液使用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]));

2

您可以使用数组作为返回值:

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] 
    ); 
} 
+1

+1,但是'MIN_VALUE'是最小的* positive *值的混淆( 0)。你最好使用'Number.INFINITY'和'Number.NEGATIVE_INFINITY' – Bergi

1

由于减少呼叫是不是真的需要在所有的,你可以有一些乐趣吧

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);

所有你真正需要的是let minMaxArray = [Math.min.apply(0,items), Math.max.apply(0,items)]

+0

非常感谢你! – vuvu

2

ES6可以使用蔓延运营商。一个字符串解决方案:

Math.min(...items)