如何使用 Ramda 按一个键分组并总结其他键? [英] How to group by a key and sum other keys with Ramda?
本文介绍了如何使用 Ramda 按一个键分组并总结其他键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的对象数组:
<预><代码>[{'prop_1':'key_1','prop_2':23,'prop_3':45},{'prop_1':'key_1','prop_2':56,'prop_3':10},{'prop_1':'key_2','prop_2':10,'prop_3':5},{'prop_1':'key_2','prop_2':6,'prop_3':7}]我想按第一个属性分组并对其他属性的值求和,得到这样的数组:
<预><代码>[{'prop_1':'key_1','prop_2':79,'prop_3':55},{'prop_1':'key_2','prop_2':16,'prop_3':12}]使用 Ramda 执行此操作的正确方法是什么?我尝试使用以下内容:
R.pipe(R.groupBy(R.prop('prop_1')),R值,R.reduce(R.mergeWith(R.add), {}))
但这也是'prop_1'的值的总和.
解决方案
您需要映射组,然后缩小每个组.检查当前合并键的值.如果值为数字,则添加值.如果不只是返回第一个值:
const { pipe, groupBy, prop, values, map, reduce, mergeWith, ifElse, is, add, identity } = Rconst fn = 管道(groupBy(prop('prop_1')),价值观,地图(减少(mergeWith(ifElse(is(Number), add, identity)),{})))const data = [{"prop_1":"key_1","prop_2":23,"prop_3":45},{"prop_1":"key_1","prop_2":56,"prop_3":10},{"prop_1":"key_2","prop_2":10,"prop_3":5},{"prop_1":"key_2","prop_2":6,"prop_3":7}]const 结果 = fn(data)console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
Suppose I have an array of objects like this:
[
{'prop_1': 'key_1', 'prop_2': 23, 'prop_3': 45},
{'prop_1': 'key_1', 'prop_2': 56, 'prop_3': 10},
{'prop_1': 'key_2', 'prop_2': 10, 'prop_3': 5},
{'prop_1': 'key_2', 'prop_2': 6, 'prop_3': 7}
]
I would like to group by the first property and sum the values of the other properties, resulting in an array like this:
[
{'prop_1': 'key_1', 'prop_2': 79, 'prop_3': 55},
{'prop_1': 'key_2', 'prop_2': 16, 'prop_3': 12}
]
What is the correct way to do this using Ramda? I have attempted to use the following:
R.pipe(
R.groupBy(R.prop('prop_1')),
R.values,
R.reduce(R.mergeWith(R.add), {})
)
But this sums also the value of 'prop_1'.
解决方案
You'll need to map the groups, and then reduce each group. Check the values of the currently merged keys. If the value is a Number add the values. If not just return the 1st value:
const { pipe, groupBy, prop, values, map, reduce, mergeWith, ifElse, is, add, identity } = R
const fn = pipe(
groupBy(prop('prop_1')),
values,
map(reduce(
mergeWith(ifElse(is(Number), add, identity)),
{}
))
)
const data = [{"prop_1":"key_1","prop_2":23,"prop_3":45},{"prop_1":"key_1","prop_2":56,"prop_3":10},{"prop_1":"key_2","prop_2":10,"prop_3":5},{"prop_1":"key_2","prop_2":6,"prop_3":7}]
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
这篇关于如何使用 Ramda 按一个键分组并总结其他键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文