nickponline
nickponline

Reputation: 25914

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

Upvotes: 1

Views: 105

Answers (2)

customcommander
customcommander

Reputation: 18901

Using reduceBy is probably a good idea. Here's an alternative in case you find it useful.

Start with an itemize function:

const itemize = ({category: c, amount: a}) => ({[c]: a});

itemize({category: 'food', amount: 5});
//=> {food: 5}

Then define a function that can either add or merge items:

const additem = mergeWith(add);

additem({food: 5}, {food: 5});
//=> {food: 10}

additem({food: 5}, {transport: 2});
//=> {food: 5, transport: 2}

Finally use these two functions in a reducer:

reduce((a, b) => additem(a, itemize(b)), {}, items);

Upvotes: 0

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16775

You could use reduceBy:

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

Upvotes: 2

Related Questions