Javascript - find max and min values using loop and array, -Infinity/Infinity

16,096

Solution 1

The key is here.

if (Numbers[i] > max) {

    max = Numbers[i];

}

If the current number is greater than the current maximum number then we make that the max number. And we continue until we go trough the entire array.

Starting with -Infinity ensures that any value in the array will be greater or equal to it.

For the minimum it's the same but we always keep the smallest value we find in the list.

Infinity and -Infinity are values javascript provides, they are greater or smaller than any other value of type Number. You can find more about them here.

You could debug your code and see exactly what's happening step by step. Check this link on how to do that in Chrome.

Solution 2

Using console, you can see that for lowest number if condition only true for once when 1 is less than Infinity. Other times it always return false because all other numbers are less then 1 so here the logic is if number from array is lower than max then it store else loop continues to looping.

Same for highest number.

//find highest number
var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = -Infinity;
var i;
for (i = 0; l > i; i++) {
  if (Numbers[i] > max) {
    console.log(i + ' max number' + Numbers[i]);
    max = Numbers[i];
  }
}
console.info(max);

//find lowest number
var Numbers = [1, 2, 101, 45, 55, 1443];
var l = Numbers.length;
var max = Infinity;
var i;
for (i = 0; l > i; i++) {
  if (Numbers[i] < max) {
    console.log(i + ' lowest number' + Numbers[i]);
    max = Numbers[i];
  }
}
console.info(max);
Share:
16,096
Jakub Mazurkiewicz
Author by

Jakub Mazurkiewicz

Updated on June 04, 2022

Comments

  • Jakub Mazurkiewicz
    Jakub Mazurkiewicz almost 2 years

    Could someone explain to me how does this work. In find highest number method every number is larger than -Infinity. Why does it take the highest number? Same with lowest number finder, how does it selects lowest number, all of the numbers are smaller than Infinity.

    //find highest number
    
    var Numbers = [1, 2, 101, 45, 55, 1443];
    var l = Numbers.length;
    var max = -Infinity;
    var i;
    for (i = 0; l > i; i++) {
    
        if (Numbers[i] > max) {
    
            max = Numbers[i];
    
        }
    
    }
    
    console.info(max);
    
    //find lowest number
    
    var Numbers = [1, 2, 101, 45, 55, 1443];
    var l = Numbers.length;
    var max = Infinity;
    var i;
    for (i = 0; l > i; i++) {
    
        if (Numbers[i] < max) {
    
            max = Numbers[i];
    
        }
    
    }
    
    console.info(max);