You have to use other method with max() to get max value element from array:-
- Spread Operator
HTML Example code:
The recommended approach is to use
Array.reduce() to find the maximum element in an array. It does compare each value of the array:
<!DOCTYPE html> <html> <body> <script> const max = arr => arr.reduce((x, y) => Math.max(x, y)); var arr = [ 16, 23, 35, 42, 59 ]; console.log("Max:", max(arr)); </script> </body> </html>
Use the Function.prototype.apply() method for finding the maximum and minimum value in a numeric array.
<script> var arr = [ 16, 23, 35, 42, 59 ]; console.log("Max:", Math.max.apply(null, arr)); </script>
Spread Operator (…)
Use the spread operator
(...) which offers the shorter syntax of writing the
apply method discussed above.
<script> var arr = [ 16, 23, 35, 42, 59 ]; console.log("Max:", Math.max(...arr)); </script>
Output: Result will be same of all above example because of same array.
Do comment if you have any doubts and suggestions on this JS array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.