pcm70 pcm70 - 2 years ago 84
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.

<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>
<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>

<script type="text/javascript">
$(document).ready(function(e) {
//Sum All Prices
var sum = 0;
sum += parseFloat($(this).text());
console.log('total: ' + sum.toFixed(2));

// Breakdown
sum = parseFloat($(this).text());

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download