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

0

I have the function:

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

When entering the array AnswerOffersList , I need to go through and get the smallest SalePrice , which in some cases has two registers for each position in the array, however, what is coming is the largest or last in the array. p>

Where am I going wrong?

    
asked by anonymous 31.03.2014 / 19:59

3 answers

3

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

The function Math.min() receives several parameters and returns the lowest. It has no way to check the variable that is getting the result.

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

I do not know if I understand how your system works, but the following code might 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);
    });
});
    
31.03.2014 / 20:25
1

You use the map function to grab 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

    
31.03.2014 / 20:45
-3

I solved it like this:

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

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

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

    });
});
    
31.03.2014 / 20:35