简体   繁体   中英

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

You could use reduceBy :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM