gpt4 book ai didi

javascript - lambda 斯 : locating items with an inner array that satisfies a spec

转载 作者:行者123 更新时间:2023-12-01 03:54:40 24 4
gpt4 key购买 nike

给定这样的结构:

[
{
documentType: { id: 4001 }
correspondence: [ { id: 1000 }, { id: 1010 } ]
},
{
documentType: { id: 102 }
correspondence: [ { id: 1000 } ]
},
{
documentType: { id: 101 }
correspondence: [ { id: 1001 } ]
}
]

我正在尝试使用 ramda 来查找内部对应数组包含 1000 的数组的索引。

我已经尝试过这个:

R.filter(R.where({ correspondence: R.any(R.where({ id: 1000 }))}))(data)

最佳答案

首先,您需要对谓词函数进行轻微调整,将内部 R.where 更改为 R.propEq 以允许与常量值而不是功能:

const pred = R.where({ correspondence: R.any(R.propEq('id', 1000))})

然后我有两个示例说明如何实现此目的,两个示例都使用 R.addIndex 来捕获索引:

使用R.reduce在测试每个元素时构建列表:

const reduceWithIdx = R.addIndex(R.reduce)
const fn = reduceWithIdx((acc, x, i) => pred(x) ? R.append(i, acc) : acc, [])

fn(data) //=> [0, 1]

第二个使用 R.map 在过滤之前将索引嵌入到每个元素中:

const mapWithIdx = R.addIndex(R.map)

const fn = R.pipe(
mapWithIdx(R.flip(R.assoc('idx'))),
R.filter(pred),
R.map(R.prop('idx'))
)

fn(data) //=> [0, 1]

关于javascript - lambda 斯 : locating items with an inner array that satisfies a spec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com