Javascript Data Structure Tutorial - Javascript Minimum and Maximum Values








The following code shows how to find the minimum value.


function findMin(arr) { //  ww  w.j a v  a  2 s. c  o m
    var min = arr[0]; 
    for (var i = 1; i < arr.length; ++i) { 
        if (arr[i] < min) { 
            min = arr[i]; 
        } 
    } 
    return min; 
} 

var nums = []; 
for (var i = 0; i < 100; ++i) { 
    nums[i] = Math.floor(Math.random() * 101); 
} 
var minValue = findMin(nums); 
console.log(); 
console.log("The minimum value is: " + minValue); 




Example

The following code shows how to find the maximum value.


function findMax(arr) { /*w ww  .ja  v a2 s  .c  om*/
    var max = arr[0]; 
    for (var i = 1; i < arr.length; ++i) { 
        if (arr[i] > max) { 
            max = arr[i]; 
        } 
    } 
    return max; 
} 

var nums = []; 
for (var i = 0; i < 100; ++i) { 
    nums[i] = Math.floor(Math.random() * 101); 
} 
var maxValue = findMax(nums); 
console.log(); 
console.log("The maximum value is: " + maxValue);