Javascript: Using reduce() to find min and max values? Javascript: Using reduce() to find min and max values? arrays arrays

Javascript: Using reduce() to find min and max values?


In ES6 you can use spread operator. One string solution:

 Math.min(...items)


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


You can use array as return value:

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