Value-finding function between Javascript variables

Asked

Viewed 1,169 times

3

I have the following form:

<body> 
    <form name="questao1" method="post" onsubmit="sendToDB();"> 
        <br><input type="checkbox" name="Q1[]" value="Enfermagem" onclick="getPontos(1)"> Garantir a saúde das pessoas 
        <br><input type="checkbox" name="Q1[]" value="Eletroeletronica" onclick="getPontos(2)"> Máquinas e instalações elétricas 
        <br><input type="checkbox" name="Q1[]" value="Informatica" onclick="getPontos(3)"> Usar lógica para fazer programas e sistemas
        <br><input type="checkbox" name="Q1[]" value="Alimentos" onclick="getPontos(4)"> Desenvolver, gerenciar e distribuir produtos alimenticios
        <br><input type="checkbox" name="Q1[]" value="Plasticos" onclick="getPontos(5)"> Desenvolver, gerenciar e distribuir produtos plásticos
        <br><input type="checkbox" name="Q1[]" value="Logistica" onclick="getPontos(6)"> Desenvolver, gerenciar e distribuir produtos
        <br><input type="checkbox" name="Q1[]" value="Administracao" onclick="getPontos(7)"> Gerenciar e influenciar pessoas a atingirem metas
        <br><input type="checkbox" name="Q1[]" value="Quimica" onclick="getPontos(8)"> Estudar, manusear e transformar substâncias ou materiais
        <br><input type="checkbox" name="Q1[]" value="Meio_Ambiente" onclick="getPontos(9)"> Estudar, manusear e transformar substâncias ou materiais da natureza
        <br><input type="checkbox" name="Q1[]" value="Mecatronica" onclick="getPontos(10)"> Projetar, usar, instalar e controlar máquinas industriais
        <br><input type="checkbox" name="Q1[]" value="Eletronica" onclick="getPontos(11)"> Sistemas  e aparelhos eletrônicos
        <br><input type="checkbox" name="Q1[]" value="Telecomunicacao" onclick="getPontos(12)"> Sistemas e aparelhos de comunicação
        <br><input type="checkbox" name="Q1[]" value="Seguranca" onclick="getPontos(13)"> Instruir e garantir a segurança das pessoas e locais
        <br><br><input type="submit" value="Próximo" onclick="finalizar()">     
    </form>
</body>

Performing the functions of

<script type="text/javascript">   
        efmg = 0; 
        eltelt = 0;
        info = 0;
        alm = 0;
        pltc = 0;
        log = 0;
        adm = 0;
        qmc = 0;
        ma = 0;
        resultado = 0;
            function getPontos(pontos){
                if (pontos == 1){ efmg = efmg + 1; }   
                if (pontos == 2){ eltelt = eltelt +1; }
                if (pontos == 3){ info = info + 1; } 
                if (pontos == 4){ alm = alm + 1;}  
                if (pontos == 5){ pltc = pltc + 1; }   
                if (pontos == 6){ log = log + 1; }  
                if (pontos == 7){ adm = adm + 1; }
                if (pontos == 8){ qmc = qmc +1; }
                if (pontos == 9){ ma = ma +1; }   
                if (pontos == 10){ mectron = mectron + 1; }     
                if (pontos == 11){ elt = elt + 1; }       
                if (pontos == 12){ tlcon = tlcon + 1; }         
                if (pontos == 13){ st = st + 1; }                     
            }      
            function finalizar(efmg,eltelt,info,alm,pltc,log,adm,qmc,ma,mectron,elt,tlcon,st){  
                if (efmg>eltelt){alert('Enfermagem');}else{alert('Eletroeletronica');} 
            }

It is working correctly, but the function finalizar() compares only two values.

Is there a Javascript function that can compare all these values by itself and find the largest among them (like the function max() in PHP)? Because it is not at all feasible to compare with if all variables to find the result.

  • There is the function max(), but where would I enter that code? It doesn’t seem that it needs this function.

  • at the end, to find the highest value that was assigned

2 answers

6

There is the function Math.max:

function getMaxOfArray(numArray) {
    return Math.max.apply(null, numArray);
}
console.log(getMaxOfArray([1,2,3,4,5,6,7,8,10]));

In your case it is possible to call the function max passing as argument the variables:

function finalizar(efmg, eltelt, info, alm, pltc, log, adm, qmc, ma, mectron, elt, tlcon, st) {
  return Math.max(efmg, eltelt, info, alm, pltc, log, adm, qmc, ma, mectron, elt, tlcon, st);
}

console.log(finalizar(3,1,2,4,5,6,12,8,2,1,3,5,9));

  • could explain to me how to use it in this case?

  • 1

    It wasn’t clear to me about what values you want to get the biggest. What would be?

  • I want to deal with the variables I’m adding up to + 1 each time I click the checkbox. These values are being assigned to a variable according to the input in the data 'points', I want to take all these variables and compare to find out which of the checkboxes the most user selected.

  • I updated the reply @Rafazanezi

  • In that case, could I assign Max.Math to a variable? Example: result = Math.max(efmg, eltelt, info, Alm, pltc, log, Adm, qmc, ma, Mectron, Elt, tlcon, st);

  • Yes, without a doubt!

  • I tried to do this but when I used in: if(result == efmg){Alert('Nursing');}Else{Alert('I don’t know');} and tested by selecting only the infermage option, it always returns 'I don’t know' Xp

  • But efmg was the highest value when you did the test case?

  • Yes, it was, yes... Then I tried the following: Alert(Math.max(efmg, eltelt, info, Alm, pltc, log, Adm, qmc, ma, Mectron, Elt, tlcon, st); to display the highest value, but he returned 'Nan'.

  • Nan is not a number, which means you were probably sending a string. If you can update the question with the new code it is easier to help :)

  • Okay, I just upgraded :)

Show 6 more comments

3


I’m going to make an improvement on the original code, but I don’t think it’s ideal, I just don’t want to change its structure too much. You can test, it’s working as you wish.

You don’t need to have multiple variables to turn into array to find the biggest, you can already create the array right from the start, thus accumulating the clicks in each element of array in only one line, just like the variable declaration only needs one line. Completion also needs only one line:

var arrayPontos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function arrayPositionMax(array) {
    var max = -Infinity;
    var position = -Infinity;
    for (i = 0; i != array.length; ++i) {
        if (array[i] > max) {
            max = array[i];
            position = i;
        }
    }
    return position;
}
function getPontos(pontos){
    arrayPontos[pontos]++;
}      
function finalizar(){  
    alert(["Enfermagem", "Eletroeletronica", "Informatica", "Alimentos", "Plasticos", "Logistica", "Administracao", "Quimica", "Meio_Ambiente", "Mecatronica", "Eletronica", "Telecomunicacao", "Seguranca"][arrayPositionMax(arrayPontos) - 1]); 
}
<form name="questao1" method="post" onsubmit=""> 
    <br><input type="checkbox" name="Q1[]" value="Enfermagem" onclick="getPontos(1)"> Garantir a saúde das pessoas 
    <br><input type="checkbox" name="Q1[]" value="Eletroeletronica" onclick="getPontos(2)"> Máquinas e instalações elétricas 
    <br><input type="checkbox" name="Q1[]" value="Informatica" onclick="getPontos(3)"> Usar lógica para fazer programas e sistemas
    <br><input type="checkbox" name="Q1[]" value="Alimentos" onclick="getPontos(4)"> Desenvolver, gerenciar e distribuir produtos alimenticios
    <br><input type="checkbox" name="Q1[]" value="Plasticos" onclick="getPontos(5)"> Desenvolver, gerenciar e distribuir produtos plásticos
    <br><input type="checkbox" name="Q1[]" value="Logistica" onclick="getPontos(6)"> Desenvolver, gerenciar e distribuir produtos
    <br><input type="checkbox" name="Q1[]" value="Administracao" onclick="getPontos(7)"> Gerenciar e influenciar pessoas a atingirem metas
    <br><input type="checkbox" name="Q1[]" value="Quimica" onclick="getPontos(8)"> Estudar, manusear e transformar substâncias ou materiais
    <br><input type="checkbox" name="Q1[]" value="Meio_Ambiente" onclick="getPontos(9)"> Estudar, manusear e transformar substâncias ou materiais da natureza
    <br><input type="checkbox" name="Q1[]" value="Mecatronica" onclick="getPontos(10)"> Projetar, usar, instalar e controlar máquinas industriais
    <br><input type="checkbox" name="Q1[]" value="Eletronica" onclick="getPontos(11)"> Sistemas  e aparelhos eletrônicos
    <br><input type="checkbox" name="Q1[]" value="Telecomunicacao" onclick="getPontos(12)"> Sistemas e aparelhos de comunicação
    <br><input type="checkbox" name="Q1[]" value="Seguranca" onclick="getPontos(13)"> Instruir e garantir a segurança das pessoas e locais
    <br><br><input type="submit" value="Próximo" onclick="finalizar()">     
</form>

I put in the Github for future reference.

If you have questions about using array can ask specific questions to learn about the subject.


The question was initially unclear as to what I wanted, so my original and other answer was simply to get as much of array, when in fact what I needed wasn’t even quite a array, although it can be used as well. The originally written solution:

I didn’t really see where it would be used, but basically I’d do it like this, because there’s a better performance.

function arrayMax(array) {
    var max = -Infinity;
    for (i = 0; i != array.length; ++i) {
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max;
}
console.log(arrayMax([5, 8, 2, 3, 6, 1]));

I put in the Github for future reference.

  • 1

    Does it perform better because it doesn’t involve method calling? Math.max is native.

  • I tried asssim: Function arrayMax(Q1) { var max = -Infinity; for (i = 0; i != Q1.length; i++) { if (Q1[i] > max) { max = Q1[i]; } } Return max; if(max = emfg){Alert('Nursing');} } but it didn’t work :(

  • 1

    @bfavaretto I don’t know the exact implementation, but I think it’s the fault of apply that will keep calling the max() in each element. If that is what you mean, then it is. You have an answer that tells you something about the concept, if you want to give it a read: http://answall.com/a/21298/101 :D

  • @Rafazanezi that’s why I said I didn’t see where you want to apply this. I actually think all this code can be done differently.

  • @Bigown did not know this answer :D may be, just seeing the same implementation.

  • @bigown I want to handle the variables I’m adding + 1 to each click on the checkbox. These values are being assigned to a variable according to the input in the data 'points', I want to take all these variables and compare to find out which of the checkboxes the most user selected.

  • 1

    https://jsperf.com/math-max-apply-vs-for

  • @Rafazanezi this I understood, I just don’t know where you want to use this because this code is very confused. I tried to give an improved.

  • @bfavaretto used his link in reply :P Thank you. I practically did another answer because it seems to be what he really wants.

Show 4 more comments

Browser other questions tagged

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