Array max js

A short note about finding the maximum value in a JavaScript array with numeric values.

The Array object in JS does not have its own max method. But we can add it.

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

We borrowed the method we are interested in from the Math object. It will work like this:

let arr = [3, 5, 6, 1, 10, '12', 0];
arr.max(); //12

If the array contains string values that cannot be cast to a number, the method returns NaN.

You can do without modifying the global Array object.

let arr = [3, 5, 6, 1, 10, '12', 56, 0];
Math.max.apply(null, arr); //56

And according to the syntax of ES6 you can write even easier

let arr = [3, 5, 6, 1, 10, '12', 56, 0];
Math.max(...arr); //56

Comments

Popular posts from this blog

JavaScript Inheritance and Classes

Typical gulpfile.js

Swipe events on touch devices