PDA

View Full Version : Max value in an array

mudd0gg
11-14-2008, 06: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, 06:46 PM
you were close:

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

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

<html>
<title>Array Max</title>
<script type="text/javascript">

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);