Easy Tutorial
❮ Csharp Foreach Android Tutorial Socket1 ❯

Finding the Maximum and Minimum Values in an Array with JavaScript

Category Programming Techniques

The algorithm for finding the minimum value is as follows:

Here is the code:

// Find the minimum value in an array
function arrayMin(arrs){
    var min = arrs[0];
    for(var i = 1, ilen = arrs.length; i < ilen; i+=1) {
        if(arrs[i] < min) {
            min = arrs[i];
        }
    }
    return min;
}
// Code test
var rets = [2,4,5,6,7,9,10,15];
console.log(arrayMin(rets));//2

The above method compares numerical values in the array. If the array contains string numbers, convert them to numbers before comparison, as string comparison is based on ASCII codes rather than values. For example, the ASCII code for "2" is greater than that for "15" because the first digit of "15" is "1", and the ASCII code for "2" is certainly greater than that for "1";

The algorithm for finding the maximum value is similar:

Here is the code:

// Find the maximum value in an array
function arrayMax(arrs) {
    var max = arrs[0];
    for(var i = 1,ilen = arrs.length; i < ilen; i++) {
        if(arrs[i] > max) {
            max = arrs[i];
        }
    }
    return max;
}
// Code test
var rets = [2,4,5,6,7,9,10,15];
console.log(arrayMax(rets));//15

** Click to Share Notes

Cancel

-

-

-

❮ Csharp Foreach Android Tutorial Socket1 ❯