pcm70 pcm70 - 22 days ago 6
jQuery Question

Grouping by matching div value with query

I am getting the total of all div values fine, but not sure how to get the breakdown of the values. How many of each div value that match. The static example is 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 at 100.00</p>
<p>3 prices at 125.95</p>
<p>1 price at 312.00</p>
<p>2 prices at 560.00</p>
</div>

<script type="text/javascript">
$(document).ready(function(e) {
//Sum All 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>

Answer

Similar to the above answer, but already did the fiddle so ¯\_(ツ)_/¯

var mappedValues = {};
var breakdownsEl = $('#breakdowns');

$('.price').each(function(index, value) {
    var itemValue = $(value).text();
    mappedValues[itemValue] ? mappedValues[itemValue]++ : mappedValues[itemValue] = 1;
});

for (var prop in mappedValues) {
    if (mappedValues.hasOwnProperty(prop)) {
      breakdownsEl.append('<p>' + mappedValues[prop] + ' prices at ' + parseFloat(prop).toFixed(2) + '</p>');
    }
};

See it live: https://jsfiddle.net/v7vrz18p/

A few optimizations, namely the check for hasOwnProperty as the object's prototype contains additional properties which technically still part of the object, are not necessary to loop through in this case.