Take larger existing value in a number array

Asked

Viewed 2,209 times

2

By giving a function, I return an array with numerous random numbers. I need to get the largest number between this array, and for that I ended up finding the function Math.max(). The problem is that I can’t get him to read my array and then return me the maximum value... basically I’m doing this:

var retorno = [3,6,9,22,46,73];
var maiorNumero = Math.max(retorno); //retornaria 73

Could someone introduce me to some solution to the fact?

2 answers

3


found(rs), inside Math.max() i have a variation to work upon programmatic arrays that works as follows:

var retorno = [3,6,9,22,46,73];
var maiorNumero = Math.max.apply(Math,retorno); //ai sim retorna 73!!

1

Another simple solution would be:

int max = array.get(0);

for ( int i = 1; i < array.length; i++) {
    if ( array.get(i) > max) {
      max = array.get(i);
    }
}
  • I agree, but the top one is already based on DOM functions, so its execution should be faster, not to mention that the writing is less =D

  • 1

    I agree that the presented by you is leaner and that is good the algorithm of my answer applies to almost any language but recommend the use of native functions =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.