Find the Max Value in an array using JavaScript function - Stack Overflow

admin2025-04-03  0

I have this function, the purpose is to find the maximum (number) element in an array, the value is ing from an argument. Can you please explain what is going on line by line with the code below.

function max(arr){
 var max = arr[0];
 for(var i=1; i<arr.length; i++){
   if(arr[i] > max){
     max = arr[i];   
   }
  }
return max;
}

max([4,12,3,8,0,22,56]); //output is 56

I have this function, the purpose is to find the maximum (number) element in an array, the value is ing from an argument. Can you please explain what is going on line by line with the code below.

function max(arr){
 var max = arr[0];
 for(var i=1; i<arr.length; i++){
   if(arr[i] > max){
     max = arr[i];   
   }
  }
return max;
}

max([4,12,3,8,0,22,56]); //output is 56
Share Improve this question edited Sep 29, 2021 at 11:10 Ruli 2,79113 gold badges33 silver badges47 bronze badges asked Feb 22, 2016 at 20:05 user5579973user5579973 3
  • 1 The function "max" set current maximum with the value of first element of the array; then in the for loop, it goes through all the elements of array (starting from element having position 1) and applies the following logic: is current element greater than current max value? If yes, current element is the new max and it tests the following element; if not, if just test the subsequent element. When all the elements of the array have been examined, the function returns max value. – Dario Commented Feb 22, 2016 at 20:16
  • What exactly are you not understanding? It marks first element as the max, and then iterates each element in the array checking if anything is actually larger. Then it returns the actual maximum. – zero298 Commented Feb 22, 2016 at 20:16
  • Thanks guys, it's a little bit clearer now, I guess I need more example like this.. something like problem and solution approach. – user5579973 Commented Feb 22, 2016 at 21:12
Add a ment  | 

6 Answers 6

Reset to default 4

Before going through the loop, your function accepts the first array element's value as a "starting"(initial) maximum. That value was 4.
On every loop iteration, each array value is pared with initial "maximum".
If the current value is bigger than previous maximum value - that current value overrides it and bees the maximum.
But ... there is much easier and better way: is to use built-in Javascript objects, like Math.
Consider the following search of max value:

var arr = [4,12,3,80,0,22,56];
var max = Math.max.apply(null, arr);
console.log(max); // 80

The above approach is preferable for searching min/max values.
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

Line one. max function is passed the array [4,12,3,8,0,22,56],

Line two. max variable is set to the first item in the array. max is 4,

Line three. A for loop is started which will start from 1 and keep looping for the length of the arr array.

Line four. Checks if the current array value is larger than the max value.

So, first time around it checks if arr[1] is greater then max. If yes, max is set to arr[1] First loop checks if (12 > 4) it is so max = 12

Second time around it checks if arr[2] is greater than max. Second loop checks if(3 > 12) it is not so max = 12

Third time around it checks if arr[3] is greater then max. Third loop checks if (8 > 12) it is not so max = 12

Fourth time around it checks if arr[4] is greater then max. Fourth loop checks if (0 > 12) it is not so max = 12

Fifth time around it checks if arr[5] is greater then max. Fifth loop checks if (22 > 12) it is so max = 22

Sixth time around it checks if arr[6] is greater then max. Sixth loop checks if (56 > 22) it is so max = 56

Line eight. The loop has finished and max is returned. max is 56

Below are three steps of your code.

  1. Your code starts to pare first element in array with next element.
  2. In if condition it check for maximum and stores in maximum (max) if the condition true.
  3. And finally returns max value.

So my suggestion is to use JavaScript inbuilt reduce method.Below are the reasons.

Math.max.apply or apply method will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters.

So use reduce method which don't have this problem

var arr = [2,4,6];
var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
});
console.log(max);

Another way to use reduce: .reduce((a,c) => c > a ? c : a, 0)

In my case, had to find all the maximum values,

var max = -Infinity, result = [];
 for (var i = 0; i < arr.length; ++i) {
    if (arr[i] < max) continue;
    if (arr[i] > max) {
      result = [];
      max = arr[i];
    }
   result.push(max);
}
return result; // in case of number of occurrences of max values return result.length;

Get max and min number of an array in javascript manually..

function max(array){
    var max= array[0];
    var min = array[0];
    for(var i=1;i<arr.length;i++){
        if(array[i]>max){
            max= array[i];
        }
        
        if(array[i]<min){
            min=array[i];
        }
        
    }
    console.log(min+","+max);
    }
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743629975a213885.html

最新回复(0)