In Javascript, given a simple number[]
array, is there an elegant way to calculate the minimum and maximum values simultaneously, or return undefined
if the array is empty?
Something like this:
const a = [1, 2, 3];
const (min, max) = minMax(a);
Pre-emptive response notes:
This is not a duplicate of this question because he is not actually calculating the min and max of the same array, but the min or max of 4 different arrays.
I want to calculate these in one pass. Not [Math.min(a), Math.max(a)]
.
I know how to do the obvious way:
let min = undefined;
let max = undefined;
for (const x of array) {
min = min === undefined ? x : Math.min(min, x);
max = max === undefined ? x : Math.max(max, x);
}
I am wondering if there is something a bit more elegant, e.g. using Array.reduce()
.
You can use Array.reduce()
to reduce into any kind of result, it doesn't have to be the same type. For example, reducing an array of numbers into an output array of two numbers, min and max:
const minMax = arr =>
arr.reduce(([min,max=min],num) => [Math.min(num,min),Math.max(num,max)], arr);
const a = [5,2,6,3,3,1,1];
const [min,max] = minMax(a);
console.log("min",min,"max",max);
The reduce
is seeded with the array itself, for brevity and because anything else is somewhat unnecessary. This would mess up arrays of length 1 due to the destructuring, so max=min
is used to set max
equal to the first element as a fallback. So cases of array length 1 or 0 are handled.