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.

1

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

var mynums = [0,0,0,2,3,4,23,435,343,23,2,34,34,3,34,3,2,1,0,0,0]; Math.max(mynums); // that returns a NaN.
Added a solution for an array.
Why is it that you have to use apply/null?
.apply passes a this reference and an array of arguments to the method you use it on. When you .apply(null, mynums) you pass each value in the array as an argument to the Math.max() function.
Most elegant in this day and age.
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)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.