Skip to content
Advertisement

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

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,
}

Advertisement

Answer

You could use reduceBy:

R.reduceBy((acc, next) => acc + next.amount, 0, R.prop('category'))(items);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement