Jquery does not return the minimum value when using Math.min( )

Asked

Viewed 122 times

0

I have the function:

$(this.SubOfferGroups).each(function () {
   $(this.AnswerOffersList).each(function () {
      menorValor = Math.min(this.SalePrice.DefaultValue);
   });
});

When entering the array AnswerOffersList, need to go through and catch the smaller SalePrice, which in some cases has two records for each position in the array, however, what is coming is the largest or last in the array.

Where am I going wrong?

3 answers

3

In addition to incorrect use of function Math.min(), there is a problem of scope.

The function Math.min() takes several parameters and returns the smallest. It has no way to verify the variable that is receiving the result.

And then you need to declare the variable menorValor out of anonymous function so that it survives more than one call.

I’m not sure I understand how your system works, but maybe the following code will solve the problem:

$(this.SubOfferGroups).each(function () {
    var menorValor = null;
    $(this.AnswerOffersList).each(function () {
        menorValor = (menorValor == null) ? 
            this.SalePrice.DefaultValue : 
            Math.min(this.SalePrice.DefaultValue, menorValor);
    });
});

1

You use the function map to take the values of all elements, and then take the minimum of all using Math.min:

var valores = $(this.SubOfferGroups).map(function () {
   return $(this.AnswerOffersList).map(function () {
      return this.SalePrice.DefaultValue;
   }).get();
}).get();

var minValor = Math.min.apply(null, valores);

Example:

jsfiddle

-3

I resolved so:

valor = this.SubOfferGroups[0].AnswerOffersList[0].SalePrice.DefaultValue;
$(this.SubOfferGroups).each(function () {

    $(this.AnswerOffersList).each(function () {

        if(valor < this.SalePrice.DefaultValue)
        {
            menorValor = valor;
        }

    });
});

Browser other questions tagged

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