通过使用 ramda 测试所有其他项目来过滤数组

Filter array by testing against all other items using ramda

我有一组人,我想针对自己进行过滤(以针对数组中的所有其他项目进行测试):

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"
}]

我曾考虑过 filterany 的组合,但并不满意。我决定在这里使用 ramda 是因为我在现有的 ramda compose 函数中使用它来转换数据。

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);

根据 regionname 的第一个字母生成的键对元素进行分组。拒绝任何长度为 1 的组,然后用 R.value 转换回数组,并展平。

注意:此解决方案将 return 多组 "identical" 人。如果你只想要一组,你可以取第一个,或者最大的一个,等等......而不是获取值和展平。

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>