Backbone集合:检索集合的不同值并对不同的值求和

时间:2014-02-13 03:59:26

标签: javascript jquery backbone.js underscore.js

与此question

相关

给出这个“样本收集数据”:

[{brand:'audi', amount: '100.16', id:'1234'},
{brand:'audi', amount: '67.84', id:'3456'},
{brand:'bmw', amount: '80.70', id:'3456'}]

如何从系列中添加不同品牌的数量?

并获取此数据:

[{brand:'audi', amount: '168.00'},
{brand:'bmw', amount: '80.70'}]

先谢谢你们!

2 个答案:

答案 0 :(得分:3)

这是一个非常标准的reduce,而且只是直接的JavaScript:

var o = data.reduce(function(m, e) {
    // There are lots of ways to do this depending on what sorts
    // of things are going to be values in `m`, we're expecting
    // the values to be non-zero numbers so a simple `!` is fine.
    if(!m[e.brand])
        m[e.brand] = 0;
    m[e.brand] += parseFloat(e.amount);
    return m;
}, { });

如果您担心石器时代的浏览器,请使用_(data).reduce或简单循环:

var o = { }, i;
for(i = 0; i < data.length; ++i) {
    if(!o[data[i].brand])
        o[data[i].brand] = 0;
    o[data[i].brand] += parseFloat(data[i].amount]);
}

对于浮点值,你应该非常安全,只要它们都很小并且像那些一样靠近。

答案 1 :(得分:1)

该解决方案首先按品牌对汽车进行分组,然后使用良好的旧减少量来计算金额:

var carsByBrand = _.groupBy(cars, 'brand');

var sumAmount = function(total, car){ 
    return total + parseFloat(car.amount); 
}

var sums = _.map( carsByBrand, function(cars, brand){
    return {
        brand: brand,
        amount: _.reduce(cars, sumAmount, 0)
    };
});