jquery - Grouping by matching div value with query -
i getting total of div values fine, not sure how breakdown of values. how many of each div value match. static example under breakdown.
<h2>prices</h2> <div id="price1" class="price">125.95</div> <div id="price2" class="price">312.00</div> <div id="price3" class="price">560.00</div> <div id="price4" class="price">100.00</div> <div id="price5" class="price">125.95</div> <div id="price6" class="price">100.00</div> <div id="price7" class="price">125.95</div> <div id="price8" class="price">560.00</div> <div id="price9" class="price">100.00</div> <div id="price10" class="price">100.00</div> <div id="totalprice"></div> <h2>breakdown</h2> <div id="breakdown"> <p>3 prices @ 100.00</p> <p>3 prices @ 125.95</p> <p>1 price @ 312.00</p> <p>2 prices @ 560.00</p> </div> <script type="text/javascript"> $(document).ready(function(e) { //sum prices var sum = 0; $('.price').each(function(){ sum += parsefloat($(this).text()); }); console.log('total: ' + sum.tofixed(2)); // breakdown $('.price').each(function(){ sum = parsefloat($(this).text()); console.log(sum.tofixed(2)); }); }); </script>
similar above answer, did fiddle ¯\_(ツ)_/¯
var mappedvalues = {}; var breakdownsel = $('#breakdowns'); $('.price').each(function(index, value) { var itemvalue = $(value).text(); mappedvalues[itemvalue] ? mappedvalues[itemvalue]++ : mappedvalues[itemvalue] = 1; }); (var prop in mappedvalues) { if (mappedvalues.hasownproperty(prop)) { breakdownsel.append('<p>' + mappedvalues[prop] + ' prices @ ' + parsefloat(prop).tofixed(2) + '</p>'); } };
see live: https://jsfiddle.net/v7vrz18p/
a few optimizations, namely check hasownproperty
object's prototype contains additional properties technically still part of object, not necessary loop through in case.
Comments
Post a Comment