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
In ES6 you can use spread operator. One string solution:
Math.min(...items)
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.
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]));
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:
|| min
check is v
number.
[Infinity, -Infinity]
is .reduce
initial value
It use js destructuring assignment
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]
);
}