Finding the Maximum and Minimum Values in an Array with JavaScript
Category Programming Techniques
The algorithm for finding the minimum value is as follows:
Assign the first element of the array to a variable, using this variable as the minimum value;
Traverse the array starting from the second element, comparing each element with the first one;
If the current element is less than the current minimum value, assign the current element's value to the minimum value;
Move to the next element and repeat step 3;
When the traversal of the array elements is complete, this variable stores the minimum value;
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:
Assign the first element of the array to a variable, using this variable as the maximum value;
Traverse the array starting from the second element, comparing each element with the first one;
If the current element is greater than the current maximum value, assign the current element's value to the maximum value;
Move to the next element and repeat step 3;
When the traversal of the array elements is complete, this variable stores the maximum value;
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
-
-
-