Javascript:使用reduce()查找最小值和最大值?

Aly*_*une 18 javascript arrays reduce

我有一个类的代码,我应该使用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;
 }
Run Code Online (Sandbox Code Playgroud)

小智 19

ES6中,您可以使用扩展运算符.一串解决方案:

 Math.min(...items)
Run Code Online (Sandbox Code Playgroud)

  • 这会因大数组而崩溃 (3认同)
  • 要详细说明@JimmyKane答案,如果使用大数组,即为`Math.min()`提供许多参数:&gt;“您冒着超过JavaScript引擎参数长度限制的风险。应用过多函数的后果参数(认为成千上万个参数)因引擎而异(JavaScriptCore的硬编码参数限制为65536),...“ https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/参考/ Global_Objects / Function / apply#Using_apply_and_built_in_functions (3认同)

小智 12

你可以这样使用。可以有任意数量的参数。

function minValue(...args) {
    const min = args.reduce((acc, val) => {
        return acc < val ? acc : val;
    });
    return min;
}

function maxValue(...args) {
    const max= args.reduce((acc, val) => {
        return acc > val ? acc : val;
    });
    return max;
}
Run Code Online (Sandbox Code Playgroud)


col*_*lxi 11

技巧包括提供一个空数组作为initialValue参数

arr.reduce(callback, [initialValue])
Run Code Online (Sandbox Code Playgroud)

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;
    }, []);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案的优点是适用于任意有序类型(例如字符串),而不仅仅是数字,这是一个很好的概括。一种可能的优化是使“initialValue”为“[items[0], items[0]]”,这样您就可以避免特殊的大小写“undefined”,简化每次调用“if (val &lt; acc[0]) acc[0] = val;` 和 `if (val &gt; acc[1]) acc[1] = val;` (4认同)

小智 7

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

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]
    );
}
Run Code Online (Sandbox Code Playgroud)

  • +1,但是“ MIN_VALUE”是令人困惑的最小“正”值(&gt; 0)。您最好使用Number.INFINITY和Number.NEGATIVE_INFINITY (3认同)
  • @Bergi我想你是说`Number.POSITIVE_INFINITY` ...没有`Number.INFINITY`。 (3认同)