Skip to content
Advertisement

Using reduce() to find min and max values?

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 reduce. The return array should be of size 2, but I know that the reduce() method always returns an array of size 1.

I’m able to obtain the minimum value using the code below, however I don’t know how to obtain the max value in that same call. I assume that once I do obtain the max value that I just push it to the array after the reduce() method finishes.

JavaScript

Advertisement

Answer

The trick consist in provide an empty Array as initialValue Parameter

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement