通过匹配div值和查询进行分组

时间:2016-11-17 18:57:47

标签: jquery

我得到所有div值的总和很好,但不确定如何得到值的细分。每个div值中有多少匹配。静态示例正在崩溃。

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

2 个答案:

答案 0 :(得分:0)

$(document).ready(function(e) {
 //Sum All Prices
                    var sum = 0;
                    var breakdown = {};
                    $('.price').each(function(){
                         value = parseFloat($(this).text()) 
                         sum += value;
                         if (breakdown[value] === undefined) {
                           breakdown[value] = 0;
                         }
                         breakdown[value]++;  
                    });
                    console.log('total: ' + sum.toFixed(2));
});

这样你就会进入一个JS对象(breakdown),你遇到一个值多少次。

然后显示它(也应该在.ready()回调中):

var breakdownElt = $('#breakdown');
for(var key in breakdown) {
  breakdownElt.append("<p>"+breakdown[key]+" price(s) at "+key+"</p>");
}

答案 1 :(得分:0)

与上面的答案类似,但已经做了小提琴,所以¯\ _(ツ)_ /¯

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>');
    }
};

现场直播:https://jsfiddle.net/v7vrz18p/

在这种情况下,一些优化,即检查hasOwnProperty作为对象的原型包含在技术上仍然是对象的一部分的附加属性,在这种情况下不需要循环。