我有一组人,我想对其自身进行过滤(以测试数组中的所有其他项目):
const people = [{
name: "James Cromwell",
region: "Australia"
}, {
name: "Janet April",
region: "Australia"
}, {
name: "David Smith",
region: "USA"
}, {
name: "Tracey Partridge",
region: "USA"
}]
在这种情况下,我想做的就是留下符合以下条件的人:
名称
以相同字母开头区域
值相同
在这种情况下,结果将是:
[{
name: "James Cromwell",
region: "Australia"
}, {
name: "Janet April",
region: "Australia"
}]
我考虑过将 filter
和 any
结合起来,但并没有什么乐趣。我决定在这里使用 ramda 是因为我在现有的 ramda compose
函数中使用它来转换数据。
最佳答案
通过从区域
生成的键和名称
的第一个字母对元素进行分组。拒绝任何长度为1的组,然后用R.value转换回数组,并展平。
注意:此解决方案将返回多组“相同”的人。如果您只想要一组,您可以采用第一个,或最大的一组,等等...而不是获取值并展平。
const { compose, groupBy, reject, propEq, values, flatten } = R
const fn = compose(
flatten, // flatten the array - or R.head to get just the 1st group
values, // convert to an array of arrays
reject(propEq('length', 1)), // remove groups with 1 items
groupBy(({ name: [l], region }) => `${region}-${l.toLowerCase()}`) // collect into groups by the requested key
)
const people = [{"name":"James Cromwell","region":"Australia"},{"name":"Janet April","region":"Australia"},{"name":"David Smith","region":"USA"},{"name":"Tracey Partridge","region":"USA"}]
const result = fn(people)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
关于javascript - 通过使用 ramda 测试所有其他项目来过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800531/