我有一个数组,我希望获得唯一的值和它们的出现次数,并总结匹配的公司名称。我正在使用lodash,到目前为止我能够获得每个独特的价值。
如何有效地获取每次出现的次数,并将它们相加?价格数据是字符串。
"typescript": ^2.0.0"
我需要的结果:
var data = [
{"cat":"IT","company":"Apple", "price":"100.5"},
{"cat":"IT","company":"Apple", "price":"100"},
{"cat":"IT","company":"Google", "price": "100"},
{"cat":"IT","company":"Apple", "price": "100"}
];
到目前为止我的代码:
Company | Count | Sum
Apple | 3 | 300.5
Google | 1 | 100
是否可以在同一个_.map函数中进行求和?
答案 0 :(得分:0)
您可以先groupBy
公司,然后map
和reduce
返回每家公司的对象数组。
var data = [
{"cat":"IT","company":"Apple", "price":"100.5"},
{"cat":"IT","company":"Apple", "price":"100"},
{"cat":"IT","company":"Google", "price": "100"},
{"cat":"IT","company":"Apple", "price": "100"}
];
var group = _.groupBy(data, 'company')
var result = _.map(_.keys(group), function(e) {
return _.reduce(group[e], function(r, o) {
return r.count += +o.price, r
}, {Company: e, count: 0, sum: group[e].length})
})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
答案 1 :(得分:0)
Array.prototype.reduce()
和Object.keys()
函数的纯JS ( Ecmascript5 )解决方案:
var data = [
{"cat":"IT","company":"Apple", "price":"100.5"},
{"cat":"IT","company":"Apple", "price":"100"},
{"cat":"IT","company":"Google", "price": "100"},
{"cat":"IT","company":"Apple", "price": "100"}
], rows = "";
var result = data.reduce(function(r, o) {
if (r[o.company]){
++r[o.company].count;
r[o.company].price += Number(o.price);
} else {
r[o.company] = {count: 1, price: Number(o.price)};
}
return r;
}, {});
Object.keys(result).forEach(function(name){
rows += '<tr><td>'+ name +'</td>' +
'<td>'+ result[name].count +'</td>' +
'<td>'+ result[name].price +'</td></tr>';
});
$('table').append(rows);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Company</th>
<th>Count</th>
<th>Sum</th>
</tr>
</table>