Jan Swart
Jan Swart

Reputation: 7221

Concat grouped values after sorting and filtering

I created a two level deep object in Ramda with groupBy statements, which I then used to sort and filter on. I now want to concatenate these arrays back into one and return that as the result of a pipe.

I have one method, but it feels really over the top for what I want to do.

Example of data:

{
    "test1": {
        "123": [
            {
                param1: "test1",
                param2: 123,
            }
        ]
    },
    "test2": {
        "456": [
            {
                param1: "test2",
                param2: 456,
            }
        ]
    },
    "test3": {
        "789": [
            {
                param1: "test3",
                param2: 789,
            },
            {
                param1: "test4",
                param2: 246,
            }
        ]
    }
}

I would like the end result of the pipe to be:

[
  {
    param1: "test1",
    param2: 123,
  },
  {
    param1: "test2",
    param2: 456,
  },
  {
    param1: "test3",
    param2: 789,
  },
  {
    param1: "test4",
    param2: 246,
  }
]

Way I have tried to get it back to an array of objects:

pipe(
  ...
  toPairs,
  map(tail),
  flatten,
  map(toPairs),
  map(map(tail)),
  flatten,
)(data)

It feels like something like this shouldn't be this difficult. Any other suggestions on how I can do this?

=============EDIT=============

I also tried this:

pipe(
  ...
  map(values),
  values,
  flatten
)(data)

Which is a little shorter, but still not sure if it is as elegant as it can be.

Upvotes: 0

Views: 126

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50797

I don't see anything more elegant than your updated suggestion. (Interestingly, without looking at yours, I came up with the same thing, except that I switched values and map(values) -- it works either way.)

I am curious, though, as to the underlying problem where you needed to do groupBy and then flatten the results. What does it do? I often use groupBy followed by values, but I don't think I've ever seen a requirement quite like yours. What's it for, if you don't mind my asking?

Upvotes: 1

Related Questions