Ramda 建议从稍微嵌套的数组中删除重复项 [英] Ramda recommendation for removing duplicates from a slightly nested array
问题描述
我们正在尝试利用 Ramda 来避免一些蛮力编程.我们有一个看起来像这样的对象数组:
<预><代码>[{id: "001", failedReason: [1000]},{id: "001", failedReason: [1001]},{id: "001", failedReason: [1002]},{id: "001", failedReason: [1000]},{id: "001", failedReason: [1000, 1003]},{id: "002", failedReason: [1000]}]我们想把它改成这样:
<预><代码>[{id: "001", failedReason: [1000, 1001, 1002, 1003]},{id: "002", failedReason: [1000]}]本质上,它根据 id 减少数组,并累积一个包含该 id 的所有failedReason"的子failedReason"数组.我们希望一些 Ramda 魔法可以做到这一点,但到目前为止我们还没有找到一个好的方法.任何想法,将不胜感激.
我无法在手机上轻松测试,但应该可以:
管道(groupBy(prop('id')),地图(采摘('failedReason')),地图(展平),地图(唯一))
更新
我刚开始在计算机上查看此内容,并注意到输出并不是您想要的.再添加两个步骤就可以解决这个问题:
管道(groupBy(prop('id')),地图(采摘('failedReason')),地图(展平),地图(唯一),对,地图(zipObj(['id','failedReason'])))
您可以在 Ramda REPL.
We're trying to utilise Ramda to avoid some brute-force programming. We have an array of objects that can look like this:
[
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1001]},
{id: "001", failedReason: [1002]},
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1000, 1003]},
{id: "002", failedReason: [1000]}
]
and we'd like to transform it so that it looks like this:
[
{id: "001", failedReason: [1000, 1001, 1002, 1003]},
{id: "002", failedReason: [1000]}
]
Essentially it reduces the array based on the id, and accumulates a sub-"failedReason" array containing all of the "failedReasons" for that id. We were hoping some Ramda magic might do this but so far we haven't found a nice means. Any ideas would be appreciated.
I can't easily test it on my phone, but something like this should work:
pipe(
groupBy(prop('id')),
map(pluck('failedReason')),
map(flatten),
map(uniq)
)
Update
I just got around to looking at this on a computer, and noted that the output wasn't quite what you were looking for. Adding two more steps would fix it:
pipe(
groupBy(prop('id')),
map(pluck('failedReason')),
map(flatten),
map(uniq),
toPairs,
map(zipObj(['id', 'failedReason']))
)
You can see this in action on the Ramda REPL.
这篇关于Ramda 建议从稍微嵌套的数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!