jQuery - Calculate percentage based on multiple conditions

Viewed 254

I have the following code:

   <script type="application/javascript"> 

    $(document).ready(function () {

        $("#market_value").on("change paste keyup", function() {
            
          var market_value = parseInt($(this).val());
            
          var data = [
          {"percent":"10","market_value":"10000"},
          {"percent":"20","market_value":"10001"},
          {"percent":"25","market_value":"20000"}
          ];
      
          for (var x in data) {
          
           if(market_value >= parseInt(data[x].market_value)) {
      
           console.log(percentage(market_value, data[x].percent));
           
           }
        
       };
           
        });
        
    function percentage(num, per)
    {
      return (num/100)*per;
    }
        
        
    });
    
    </script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<input type="text" class="form-control" id="market_value" name="market_value" value="">

I just need a simple code to calculate the percentage of the market_value based on the JSON data list.

For example:

If I type 8000 result must be 800 (10% based on the "percent" field).

If I type 11000 result must be 2200 (20% based on "percent" field because is highest than 10001)

If I type 50000 result must be 12500 (25% based on "percent" field because is highest than 20000)

If I type 3000 result must be 300 (10% based on "percent" field because is NOT highest than 10000)

The code I made is working in some way but if I type a number lower than 10000 then nothing shows.

These are not fixed values, the data (JSON) is dynamic.

2 Answers

As @Andreas@ and @John@ correctly pointed out, the loop will end without any action:

for (var x in data) {
    if(market_value >= parseInt(data[x].market_value)) {    // never happens for <10000
    console.log(percentage(market_value, data[x].percent));
}

Why?

Let's say we give market_value = 5555.
Now as the for goes down the road, in your case it will perform the following comparisons:

if( 5555 >= 10000 ) { ... }
if( 5555 >= 10001 ) { ... }
if( 5555 >= 10002 ) { ... }

All these conditions will give you false. That's the core of the problem.

Suggestion to fix it

  • Either you introduce a fourth condition with a low limit (e.g. zero)
  • or you manage the "none of the above" case after the for loop.

I managed to solve it that way:

var data = [
      {"percent":"10","market_value":"10000"},
      {"percent":"25","market_value":"20000"},
      {"percent":"20","market_value":"10001"}
      ];

   sorted_data = sortByKeyDesc(data, "market_value");

   for (var x in sorted_data) {
  
   if(market_value >= parseInt(sorted_data[x].market_value)) {

   console.log(percentage(market_value, sorted_data[x].percent));

   break;

   }else if(market_value){
   console.log(percentage(market_value, sorted_data[x].percent));   
   }


 function sortByKeyDesc(array, key) {
    return array.sort(function (a, b) {
        var x = a[key]; var y = b[key];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
}

Because json data sometimes can not be in that order (lowest to highest) first I sort them by highest market_value and then I run the percentage function. If value is 1 - 10000 then apply the 10% (which is the last row)

I do not know how dirty is that but is working very well. If someone else have a better idea I would be happy to see it.

Related