Home > Net >  How do I sum a key and group by value using Ramda?
How do I sum a key and group by value using Ramda?

Time:12-09

I have data like this:

const items = [
  {category: 'food', amount: 5},
  {category: 'food', amount: 5},
  {category: 'transport', amount: 2},
  {category: 'travel', amount: 11},
  {category: 'travel', amount: 1},
]

How can I sum amount and group by each category yielding:

{
  food : 10,
  transport : 2,
  travel : 12,
}

CodePudding user response:

You could use reduceBy:

R.reduceBy((acc, next) => acc   next.amount, 0, R.prop('category'))(items);
  • Related