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

后端 未结 11 613
野性不改
野性不改 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: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]));

提交回复
热议问题