shlagwuk shlagwuk - 28 days ago 23
Javascript Question

groupBy array of objects with underscore.js

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}
];

Answer

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