1

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

2 Answers 2

1

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});
});
Sign up to request clarification or add additional context in comments.

1 Comment

Well, that was easy :-) Thanks!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.