Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid this NaN result using Math.max.apply()?

How to best avoid this result, given the situation below?

var p = ["!NUM", 35,2,65,7,8,9,12,121,33,99];

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

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

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to filter out the non-numbers before trying to find the maximum. For example:

Array.prototype.max = function() {
    return Math.max.apply(null, this.filter(n => !isNaN(n)))
}

But I would recommend not adding new methods to built-in classes like Array. It’s better to make your own module or class that has utility functions/methods in a namespace you control. I’d be inclined to define your max as a function that takes an array parameter instead of a method:

const max = ary => Math.max.apply(null, ary.filter(n => !isNaN(n)))

which you would then call as max(p) instead of p.max().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading