Reputation: 761
I have an array where I would like to get the unique values and the number of their occurrences, and sum the matching company names. I'm using lodash, and so far I'm able to get each unique value.
How can i efficiently get the number of each occurrence, and sum them? Price data is strings.
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"}
];
Result I need:
Company | Count | Sum
Apple | 3 | 300.5
Google | 1 | 100
My code so far:
var result = _.map(_.uniqBy(data, 'company'), function (item) {
$('table').append('<tr><td>'+item.company+'</td></tr>');
});
Is it possible to do sum and count inside the same _.map function?
Upvotes: 3
Views: 4182
Reputation: 92854
Pure JS(Ecmascript5) solution using Array.prototype.reduce()
and Object.keys()
functions:
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>
Upvotes: 5
Reputation: 122047
You can first groupBy
company and then map
and reduce
to return array of objects for each company.
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>
Upvotes: 2