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

时间:2019-04-22 20:14:22

标签: javascript arrays ramda.js

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

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

我看过结合使用filterany,但并不高兴。我在这里使用ramda的决定是,我将在现有的ramda compose函数中使用它来转换数据。

2 个答案:

答案 0 :(得分:5)

通过从regionname的第一个字母生成的密钥对元素进行分组。拒绝任何长度为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);