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);
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):
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With