2

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:

  1. 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.

  2. I want to calculate these in one pass. Not [Math.min(a), Math.max(a)].

  3. 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().

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • there is no `Math.reduce` function, do you mean `Array.reduce`? And if so, just put your `for of` loop in the `reduce` function and you're done. – pretzelhammer Jun 24 '20 at 13:58
  • Ah yeah oops, thanks! And it isn't as simple as that because the input and output of `reduce` have to be the same type. I could do `array.map(x => [x, x]).reduce(...)` but euurgh. Not my idea of elegant. – Timmmm Jun 24 '20 at 14:00
  • `array.reduce(([min,max], x)=>[Math.min(min,x),Math.max(max,x)],[,,].fill(array[0]))`? – user120242 Jun 24 '20 at 14:09

4 Answers4

6

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.

Klaycon
  • 10,599
  • 18
  • 35
  • It doesn't really matter, but this will fail if the array is 1 length, add default value `,max=min]` or something – user120242 Jun 24 '20 at 14:11
  • just change max to max=min, so it defaults to the first value. your answer would be technically more correct than his, because it handles the empty set – user120242 Jun 24 '20 at 14:16
  • @user120242 hm! TIL about defaults in destructured parameters! thanks, was sure that would error out – Klaycon Jun 24 '20 at 14:16
  • really personal opinion-based and debatable comment I'm going to make here, but I'd recommend putting the part after the arrow on a newline. It gets cut off because the line is too long, and it's hard to read like that, even if it was fully visible. Makes it look obfuscated – user120242 Jun 24 '20 at 14:22
  • This is the sort of thing I was thinking of! Maybe a bit *too* clever - took me a few minutes to noticed the array destructuring - but nice answer! – Timmmm Jun 25 '20 at 08:28
5

Using Array.reduce and only iterating over the array once. I'm using array destructing assignment to pass back both min and max values from the function (since JS doesn't have tuple types). I'm also checking for the edge cases of the array being empty:

function minMax(array) {
  if (array.length == 0) {
    return [undefined, undefined];
  }
  return array.reduce(([min, max], val) => {
    return [Math.min(min, val), Math.max(max, val)];
  }, [Number.MAX_VALUE, Number.MIN_VALUE]);
}

function testMinMax(array) {
  let [min, max] = minMax(array);
  console.log(min, max);
}

testMinMax([]); // logs "undefined undefined"
testMinMax([1]); // logs "1 1"
testMinMax([1, 2, 3, 4, 5]); // logs "1 5"
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
1

With spread operator combining with Math.min and Math.max

const a = [1, 2, 3];

const [min, max] = [Math.min(...a), Math.max(...a)];

console.log({min, max});
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

Why not just this:

function minMax(arr) {
    arr = arr.sort((a, b) => a - b);
    return [arr.at(0), arr.at(-1)]
}
const a = [1, 2, 3];
const [ min, max ] = minMax(a);
shaedrich
  • 5,457
  • 3
  • 26
  • 42