Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Max value in an array

1. ## Max value in an array

Hi all,

Just looking for a simple bit of code, just to find the max value in an array when the elements are known e.g:

var v=[10,8,42,50] // So looking to find 50

I've tried using Math.max e.g:

But i guess it doesnt work the same way for arrays as it does variables as the above just puts out the whole array e.g:

10,8,42,50 // The output when code is run

• you were close:
Code:
```var v=[10,8,42,50] // So looking to find 50

• ## Alternate solutions ...

Two other methods to search values in an array, although not as brief ...
PHP Code:
``` <html> <head> <title>Array Max</title> <script type="text/javascript"> // From: http://codingforums.com/showthread.php?t=152260 var v=[10,8,42,50] // So looking to find 50 function srchMaxV() {   var maxV = 0;  // or value smaller that smallest in array to search, like = -1000;   for (i=0; i<v.length; i++) {      if (v[i] > maxV) { maxV = v[i]; }   }   return maxV; } function NumSort(a,b) { return a-b; }  // required for sorting numbers only function sortMaxV() {   var sortedV = new Array();   sortedV = v.sort(NumSort);   alert('Max: '+sortedV[sortedV.length-1]+'\nMin: '+sortedV[0]); } </script> </head> <body>   <button onclick="alert('Max: '+srchMaxV())">Search for Max</button>   <button onclick="sortMaxV()">Sort for Max/Min</button> </body> </html>  ```
Hopefully makes understanding what's going on better.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•