Home > Software engineering >  How to avoid this NaN result using Math.max.apply()?
How to avoid this NaN result using Math.max.apply()?

Time:11-23

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.

CodePudding user response:

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().

  • Related