Finding the Minimum and Maximum Elements of an Array in JavaScript
Determining the smallest and largest values within a JavaScript array is a common task. The built-in Array object provides methods to obtain these values, but it's also possible to augment the Array prototype to perform these operations.
Augmenting the Array Prototype
The Array prototype can be modified to use the Math.max and Math.min functions. This approach seamlessly integrates these operations within the Array object itself:
Array.prototype.max = function() { return Math.max.apply(null, this); }; Array.prototype.min = function() { return Math.min.apply(null, this); };
Example Usage
To use the augmented Array methods:
let p = [35, 2, 65, 7, 8, 9, 12, 121, 33, 99]; console.log(`Max value is: ${p.max()}`); console.log(`Min value is: ${p.min()}`);
Output:
Max value is: 121 Min value is: 2
The above is the detailed content of How to Find the Minimum and Maximum Values in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!