gosseti
gosseti

Reputation: 975

Filter array by testing against all other items using ramda

I have an array of people that I would like to filter against itself (to test against all other items in the array):

const people = [{
  name: "James Cromwell",
  region: "Australia"
}, {
  name: "Janet April",
  region: "Australia"
}, {
  name: "David Smith",
  region: "USA"
}, {
  name: "Tracey Partridge",
  region: "USA"
}]

What I would like to do in this case is to be left with any people whose:

In this case the result would be:

[{
  name: "James Cromwell",
  region: "Australia"
}, {
  name: "Janet April",
  region: "Australia"
}]

I’ve looked at doing a combination of filter and any but with no joy. My decision to use ramda here is that I’m using this in an existing ramda compose function to transform the data.

Upvotes: 0

Views: 99

Answers (2)

Ori Drori
Ori Drori

Reputation: 192422

Group the elements by a key generated from the region and the 1st letter of the name. Reject any group with length 1, and then convert back to array with R.value, and flatten.

Note: this solution will return multiple groups of "identical" people. If you want only one group, you can take the 1st one, or the largest one, etc... instead of getting the values and flattening.

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>

Upvotes: 5

junvar
junvar

Reputation: 11594

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

Upvotes: -1

Related Questions