2017-04-23 121 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)