且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-26 19:42:04

诀窍在于提供一个empty Array as initialValue参数

The trick consist in provide an empty Array as initialValue Parameter

arr.reduce(callback, [initialValue])




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.

所以代码看起来像这个:

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