ctp
ctp

Reputation: 1087

Elixir Enum, filter and group

what's the most elegant way in Elixir to transform

[["A","B","foo"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]]

into:

[["A","B","foo","bar","baz"],["C","D","foobar","bla"],["E","F","blabla"]]

Basically I want to iterate over the input list and group by the first two elements.

Upvotes: 1

Views: 564

Answers (1)

Dogbert
Dogbert

Reputation: 222428

I'd group by Enum.take(2) and then flat_map each group with Enum.drop(2):

[["A","B","foo"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]]
|> Enum.group_by(&Enum.take(&1, 2))
|> Enum.map(fn {key, value} ->
  key ++ Enum.flat_map(value, &Enum.drop(&1, 2))
end)
|> IO.inspect

Output:

[["A", "B", "foo", "bar", "baz"], ["C", "D", "foobar", "bla"],
 ["E", "F", "blabla"]]

Note that this will also work if any item in the input list has > 3 elements; in that case it'll just concat them:

[["A","B","foo","z","zz"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]]

will output:

[["A", "B", "foo", "z", "zz", "bar", "baz"], ["C", "D", "foobar", "bla"],
 ["E", "F", "blabla"]]

Upvotes: 2

Related Questions