简体   繁体   English

如何使用 Ramda 按值对键和分组求和?

[英]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:如何按每个category汇总amount和分组,得出:

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

You could use reduceBy :您可以使用reduceBy

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

Using reduceBy is probably a good idea.使用reduceBy可能是个好主意。 Here's an alternative in case you find it useful.如果您发现它有用,这里有一个替代方案。

Start with an itemize function: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:然后定义一个 function 可以添加或合并项目:

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:最后在reducer中使用这两个函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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