4

I want to create a function which returns the maximum number from an array, but it keeps returning NaN.

How can I prevent NaN and return the wanted result ?

var thenum = [5,3,678,213];

function max(num){
    console.log(Math.max(num));
}

max(thenum);                                                                      
gvlasov
  • 18,638
  • 21
  • 74
  • 110
Osiris
  • 45
  • 1
  • 4

4 Answers4

7

The reason why this is happening is that Math.max calculates the maximum out of its parameters. And seen as the first parameter is an Array it returns NaN.

You now have 2 options (depending on your environment or preference):

ES6 (with spread syntax)

You can spread the array to the params of the function.

const thenum = [5, 3, 678, 213];

console.log(Math.max(...thenum));

More on the spread syntax

And here is a jsFiddle with this example.


ES5 (without spread syntax)

Or, you can call it using the apply method which allows you to call functions and send the parameters for them within an array.

What you want is to apply the Math.max function, like so:

var thenum = [5, 3, 678, 213];

function max(num){
    return Math.max.apply(null, num);
}

console.log(max(thenum));

You can also make it a method and attach it to the Array prototype. This way you can use it easier and cleaner (overwriting the prototype is dangerous and you should probably avoid it - Read more about it). Like so:

Array.prototype.max = function () {
    return Math.max.apply(null, this);
};
console.log([5, 3, 678, 213].max());

More on the apply method.

And here is a jsFiddle with both

Ciprian Mocanu
  • 2,166
  • 3
  • 25
  • 44
1

try this one. Math.max.apply(Math,thenum)

var thenum = [5,3,678,213];

function max(num){
    console.log(Math.max.apply(Math,thenum));
}

result: 678

Dyrandz Famador
  • 4,499
  • 5
  • 25
  • 40
1

The Math.max() method doesn't allow you to pass in an array. So for Array you have to do using Function.prototype.apply(), e.g.

Math.max.apply(null, Array);

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0
var p = [35,2,65,7,8,9,12,121,33,99];

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};


alert("Max value is: "+p.max()+"\nMin value is: "+ p.min());  

demo

ozil
  • 6,930
  • 9
  • 33
  • 56