View Full Version : Max value in an array

11-14-2008, 05:24 PM
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

rnd me
11-14-2008, 05:46 PM
you were close:

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

11-14-2008, 05:56 PM
Two other methods to search values in an array, although not as brief ... :o

<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]);
<button onclick="alert('Max: '+srchMaxV())">Search for Max</button>
<button onclick="sortMaxV()">Sort for Max/Min</button>

Hopefully makes understanding what's going on better. :thumbsup: