2

What is the best way to get the min and max of an array into two variables? My current method feels lengthy:

var mynums = [0,0,0,2,3,4,23,435,343,23,2,34,34,3,34,3,2,1,0,0,0]
var minNum = null;
var maxNum = null;
for(var i = 0; i < mynums.length; i++) {
  if(!minNum) {
    minNum = minNum[i];
    maxNum = maxNum[i];
  } else if (mynums[i] < minNum) {
    minNum = mynums[i];
  } else if (mynums[i] > minNum && mynums[i] > maxNum) {
    maxNum = mynums[i]
  }
}

Other posts that appear to 'address' this seem to be old and I feel like there must be a better way in 2017.

Rolando
  • 58,640
  • 98
  • 266
  • 407
  • Possible duplicate of [JavaScript: min & max Array values?](http://stackoverflow.com/questions/1669190/javascript-min-max-array-values) – Dave Apr 24 '17 at 22:17

3 Answers3

5

You can just use Math.max() and Math.min()

For an array input, you can do

var maxNum = Math.max.apply(null, mynums);

var minNum = Math.min.apply(null, mynums);
NS0
  • 6,016
  • 1
  • 15
  • 14
0

You can use reduce() and find both min and max at the same time.

var mynums = [0, 0, 0, 2, 3, 4, 23, 435, 343, 23, 2, 34, 34, 3, 34, 3, 2, 1, 0, 0, 0]

var {min, max} = mynums.reduce(function(r, e, i) {
  if(i == 0) r.max = e, r.min = e;
  if(e > r.max) r.max = e;
  if(e < r.min) r.min = e;
  return r;
}, {})

console.log(min)
console.log(max)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

As an alternative, use Lodash min and max functions.

var mynums = [0,0,0,2,3,4,23,435,343,23,2,34,34,3,34,3,2,1,0,0,0];
var minNum = _.min(mynums); // 0
var maxNum = _.max(maxNum); // 435

And take a look at minBy and maxBy functions which also could be very useful.