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.
/** * Takes an array of numbers and returns an array of size 2, * where the first element is the smallest element in items, * and the second element is the largest element in items. * * Must do this by using a single call to reduce. * * For example, minMax([4, 1, 2, 7, 6]) returns [1, 7] */ function minMax(items) { var minMaxArray = items.reduce( (accumulator, currentValue) => { return (accumulator < currentValue ? accumulator : currentValue); } ); return minMaxArray; }
reduce() method. const value = array. reduce(callback[, initialValue]); The callback is an obligatory argument that is a function performing the reduce operation, and the second optional argument is the initial value.
The easiest and perhaps most popular use of the JavaScript reduce method is to get the sum total of a list of numbers. On every iteration, we simply added the current teams' points to the previously accumulated points, and then we returned that as the accumulated value for the next iteration.
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; }, []); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With