我想对自己进行过滤(以对数组中的所有其他项目进行测试):
const people = [{
name: "James Cromwell",
region: "Australia"
}, {
name: "Janet April",
region: "Australia"
}, {
name: "David Smith",
region: "USA"
}, {
name: "Tracey Partridge",
region: "USA"
}]
在这种情况下,我想做的就是与以下任何人在一起:
name
以相同的字母开头region
的值相同在这种情况下,结果将是:
[{
name: "James Cromwell",
region: "Australia"
}, {
name: "Janet April",
region: "Australia"
}]
我看过结合使用filter
和any
,但并不高兴。我在这里使用ramda的决定是,我将在现有的ramda compose
函数中使用它来转换数据。
答案 0 :(得分:5)
通过从region
和name
的第一个字母生成的密钥对元素进行分组。拒绝任何长度为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>
答案 1 :(得分:-1)
const people = [{
name: "James Cromwell",
region: "Australia"
}, {
name: "Janet April",
region: "Australia"
}, {
name: "David Smith",
region: "USA"
}, {
name: "Tracey Partridge",
region: "USA"
}];
let output = people
.filter((p1, i1) =>
people.some((p2, i2) =>
i1 !== i2 && p1.region === p2.region && p1.name[0] === p2.name[0]));
console.log(output);