Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Oct 2008
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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:

    alert(Math.max(v));

    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

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,349
    Thanks
    11
    Thanked 589 Times in 570 Posts
    you were close:
    Code:
    var v=[10,8,42,50] // So looking to find 50
    alert(Math.max.apply(0,v));
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,087
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb 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=0i<v.lengthi++) { 
        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
    •