How to know the highest value of an Array?

6

I'm doing 1 calculator that adds values entered by the user and when the values of the sums reach 1000 or exceed, the loop ends.

So far so good, the problem is to be able to identify the highest value entered by the user

Each time the loop rotates, I put the current value of var = i into an array so that all values entered by the user are stored in it.

At the end all values will be inside the array, but how do you find the largest of them?

    
asked by anonymous 08.10.2014 / 04:54

4 answers

15

In JS this is very simple:

Math.max.apply(null, meuArray );


Usage example:

var meuArray= [0,12,13,2,1273,28,1];
var maior = Math.max.apply(null, meuArray );

document.getElementById( 'resultado' ).innerHTML = maior;
<div id="resultado"></div>

The apply works as if you had passed the array values as parameters of the max function, and would be equivalent to typing Math.max(0,12,13,2... . The first parameter is equivalent to the scope to be used in the function, and in this case, of course, we pass null , which represents the global scope.

If your array has much more than one million items, which is usually not the case, you can use a loop solution.


Workaround: loop . (didactic example)

var maior = 0;
for (var i = 0; i < meuArray.length; i++) {
   if ( meuArray[i] > maior ) {
      maior = meuArray[i];
   }
}
    
08.10.2014 / 05:08
6

When I need to know the largest number in an array then I make a .sort() .

For example:

[4,3,6,9].sort(function(a, b){return b - a;})

returns [9, 6, 4, 3] , then I only need to fetch the first element. That is:

var elMaximo = [4,3,6,9].sort(function(a, b){return b - a;})[0];
    
08.10.2014 / 07:12
6

If there is already a cycle that occurs for receiving the numbers entered, I believe that you could also solve the problem of determining the largest number by creating a variable that always stores the highest value of the numbers entered.

Example (assuming you are using do while ):

    ...
    var maior = 0;
    do
    {
       if (numeroInserido > maior ) {
          maior = numeroInserido;
       }    
       // aqui podes vai o código responsável pela soma e restante validação do limite
       // máximo do valor 1000        
    }while (...)

In this solution you will not need to store the values in a array to determine the largest number you typed.

Note: I assumed that you keep the numbers in an array so that you can later determine the largest of them.

    
08.10.2014 / 10:42
1

To find the largest number in a set of variables you can use the max function of Math:

var a = 10;
var b = 25;
var c = 20;
maior = Math.max(a,b,c); 
console.log(maior) //25

It accepts multiple arguments so you can use spread (...) to use with arrays

var numeros = [1,2,5,200,89,5,50];
var maior = Math.max(...numeros);
console.log(maior) //200

As the name says, it "spreads" the array by turning it into several separate arguments

    
30.03.2018 / 03:31