Rolando
Rolando

Reputation: 62596

How to get the min and max of an array of numbers in javascript?

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.

Upvotes: 2

Views: 142

Answers (3)

Yury Pushnov
Yury Pushnov

Reputation: 1

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.

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

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)

Upvotes: 0

NS0
NS0

Reputation: 6096

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);

Upvotes: 5

Related Questions