Compare two numbers and pick the biggest

Asked

Viewed 1,764 times

0

Hello guys I’m creating this script to check the largest number and apply it as discount, but I’m having trouble identifying the largest number and do the calculation.

Doubt is how to take the values with the comma and return the highest value.

$('.item').each(function() {
	var item = $(this);
	var flag = item.find('.flag');
	var value;
	
    //ESTE IF VERIFICA SE TEM MAIS DE 1 FLAG 
    //QUERO RETORNAR O NUMERO MAIOR COM PONTO OU VIRGULA ENTRE AS 2 FLAGS
	if(flag.length > 1){
        flag.each(function() {
            value = $(this).text().replace(/[^0-9]/g, '');
            console.log(value);
        });
    };
});
*{margin:0;padding:0;list-style:none;font-family:sans-serif;box-sizing:border-box}
ul{display:flex;justify-content:space-around}
.item{padding:10px;width:30%;float:left;border:1px solid #000}
.flag,.console-log{margin:5px 0;padding:5px 0;color:#FFF;text-align:center;background-color:#1485D3}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li class="item">
        <p class="flag 1897----promo-comprador">18,97% - Promo Comprador</p>
        <p class="flag 8131----desconto-no-boleto">8,131% - Desconto no Boleto</p>
        <p id="" class="console-log"></p>
    </li>

    <li class="item">
        <p class="flag 1897----promo-comprador">18,97% - Promo Comprador</p>
        <p class="flag 8131----desconto-no-boleto">8,131% - Desconto no Boleto</p>
        <p id="" class="console-log"></p>
    </li>

    <li class="item">
        <p class="flag 1897----promo-comprador">18,97% - Promo Comprador</p>
        <p class="flag 8131----desconto-no-boleto">8,131% - Desconto no Boleto</p>
        <p id="" class="console-log"></p>
    </li>
</ul>

  • Do you have access to HTML to the point where you can change it? If so, it makes more sense for you to add an attribute to the tags p: <p data-percentual="18.97">...</p>

  • @Uilque Messias I don’t have access, this is generated from a system so I have to work with that same.

3 answers

5

you will need to include . and , its regular expression, then transform its string to a valid decimal.

// lista de textos que contem um valor decimal.
var textos = [
  "18,97% - Promo Comprador",
  "8,131% - Desconto no Boleto"
];

// extraindo os valores com ponto flutuante dos textos.
var valores = textos.map(function (texto, indice) {
  return texto.replace(/[^0-9,]/g, '').replace(",", ".");
});

// obtendo o maior valor dentro do array.
var maior = Math.max(...valores);

console.log(maior);

  • 1

    You can use Math.max.apply to compare the largest numbers.

  • 1

    @Klaiderklai, thanks for the suggestion.

  • @Tobymost Wow! I didn’t know it existed ... within the Javascript argument expression... you know the name of these 3 points?

  • 1

    @Klaiderklai, also did not know the name of the same, but once asked, I found them on quick search.: spread operator

  • @hydroper me tbm did not know that existed in JS this... always opted to make a great line of code to go through all values (Living and learning really...)

1

You can change the regex to facilitate the search and then exchange the , for . (for the method parseFloat works in the standard en-US):

$('.item').each(function() {
    var greaterValue = -99999, greaterFlag = null;
	
    $(this).find('.flag').each(function() {
        var textValue = $(this).text().replace(/^([0-9]+)\,([0-9]+)\%.*$/, '$1.$2');
        var numericValue = parseFloat(textValue);

        if(!isNaN(numericValue) && numericValue > greaterValue) {
            greaterValue = numericValue;
            greaterFlag = $(this); // pega a tag <p/> atual
        }
    });

    console.log('greater value: ' + greaterValue + ' | greater flag tag: ' + greaterFlag.text());
});
*{margin:0;padding:0;list-style:none;font-family:sans-serif;box-sizing:border-box}
ul{display:flex;justify-content:space-around}
.item{padding:10px;width:30%;float:left;border:1px solid #000}
.flag,.console-log{margin:5px 0;padding:5px 0;color:#FFF;text-align:center;background-color:#1485D3}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li class="item">
        <p class="flag 1897----promo-comprador">18,97% - Promo 1 Comprador</p>
        <p class="flag 8131----desconto-no-boleto">8,131% - Desconto 1 no Boleto</p>
        <p id="" class="console-log"></p>
    </li>

    <li class="item">
        <p class="flag 1897----promo-comprador">1,24% - Promo 2 Comprador</p>
        <p class="flag 8131----desconto-no-boleto">89,131% - Desconto 2 no Boleto</p>
        <p id="" class="console-log"></p>
    </li>

    <li class="item">
        <p class="flag 1897----promo-comprador">11,9737% - Promo 3 Comprador</p>
        <p class="flag 8131----desconto-no-boleto">2,00% - Desconto 3 no Boleto</p>
        <p id="" class="console-log"></p>
    </li>
</ul>

0

Use Math.max.apply to compare the numbers. To solve the comparison, try to base yourself on this specific code:

$('.item').each(function() {

    var item = $(this);
    var flag = item.find('.flag');

    /* Array com números das flags do item */
    var numbers = [];

    /* Percorre sobre cada flag */
    flag.each(function(f) {

        // Tira o número da flag da string e adiciona para a array;
        numbers.push(
            parseFloat($(f).text().replace('.', ','))
        );

    });

    // Pega o número máximo na array
    var max = Math.max.apply(null, numbers);

    // Loga o número máximo no console do navegador
    console.log(max);

});

Browser other questions tagged

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