Reputation: 93
I have a array (order) of objects (products): , I want to group and count all these products by id:
var order = [
{ product_id: 70, product_price: 9, product_color: "ccc"},
{ product_id: 70, product_price: 9, product_color: "ccc"},
{ product_id: 71, product_price: 10, product_color: "fff" } ];
with Underscore.js:
var groups = _.countBy(order, function(value){
return value.product_id + "#" + value.product_price + "#" + value.product_color;
})
//--> Object {70#ccc#9: 2, 71#fff#10: 1}
So it works… but now, how can I return theses values into an array like this, so I can work with this as a new array of objects?
[
{ product_id: 70, product_price: 9, product_color: "ccc", count: 2},
{ product_id: 70, product_price: 9, product_color: "fff", count: 1}
];
Upvotes: 1
Views: 1148
Reputation: 11600
You can use reduce to recreate the original array.
var countedById = [
{ product_id: 70, product_price: 9, product_color: "ccc", count: 2},
{ product_id: 70, product_price: 9, product_color: "fff", count: 1}
];
var original = countedById.reduce((acc, cur) => {
for (var i = 0; i < cur.count; i++) {
var original = {
product_id: cur.product_id,
product_price: cur.product_price,
product_color: cur.product_color
}
acc.push(original);
}
return acc;
}, []);
document.write(JSON.stringify(original))
Upvotes: 0
Reputation: 27976
Instead of countBy you could use groupBy and then map across the groups to add the count:
var groups = _.groupBy(order, function(value){
return value.product_id + "#" + value.product_price + "#" + value.product_color;
})
groups = _.map(groups, function(group){
return _.extend(group[0], {count: group.length});
});
Upvotes: 1