[removed] Using reduce() to find min and max values?

后端 未结 11 587
野性不改
野性不改 2020-12-09 15:46

I have this code for a class where I\'m supposed to use the reduce() method to find the min and max values in an array. However, we are required to use only a single call to

11条回答
  •  既然无缘
    2020-12-09 16:05

    The trick consist in provide an empty Array as initialValue Parameter

    arr.reduce(callback, [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;
        }, []);
    }
    

提交回复
热议问题