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

后端 未结 11 575
野性不改
野性不改 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 15:48

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

     Math.min(...items)
    
    0 讨论(0)
  • 2020-12-09 15:50

    I know this has been answered but I went off of @Sergey Zhukov's answer (which seems incomplete) and was able to get the min and max values in 2 lines:

    let vals = [ numeric values ]
    let min = Math.min.apply(undefined, vals) 
    let max = Math.max.apply(undefined, vals)
    

    I do see the value in Array.reduce, but with such a super simple use case, and so long as you understand what Function.apply does, this would be my goto solution.

    0 讨论(0)
  • 2020-12-09 15:52

    The solution using Math.min() and Math.max() functions:

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

    0 讨论(0)
  • 2020-12-09 15:59

    let arr = [8978, 'lol', -78, 989, NaN, null, undefined, 6, 9, 55, 989];
    
    
    let minMax = arr.reduce(([min, max], v) => [
                    Math.min(min, v) || min,
                    Math.max(max, v) || max], [Infinity, -Infinity]);
    
    
    console.log(minMax);

    How it works:

    1. || min check is v number.

    2. [Infinity, -Infinity] is .reduce initial value

    3. It use js destructuring assignment

    0 讨论(0)
  • 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;
        }, []);
    }
    
    0 讨论(0)
  • 2020-12-09 16:05

    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]
        );
    }
    
    0 讨论(0)
提交回复
热议问题