Денис Корх
Денис Корх

Reputation: 353

Elixir - merge list elements

I have a list

extensions = [
  [
    %{extension: "zip", size: 3627, type: "archives"},
    %{extension: "xml", size: 3627, type: "documents"}
  ],
  [
    %{extension: "png", size: 458605, type: "graphics"},
    %{extension: "png", size: 458605, type: "graphics"}
  ]
]

I need to merge list elements to get:

extensions = [
    %{extension: "zip", size: 3627, type: "archives"},
    %{extension: "xml", size: 3627, type: "documents"},
    %{extension: "png", size: 458605, type: "graphics"},
    %{extension: "png", size: 458605, type: "graphics"}
]

I can not find the right solution. I would be grateful for your help.

Upvotes: 1

Views: 2846

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

While the answer provided by @Daniel is perfectly correct in this particular case, one needs to be cautious with List.flatten/1, since it flattens deeply. The precise answer to the question stated would be

extensions
|> :lists.reverse()
|> Enum.reduce(&++/2)

To understand the difference, let’s consider we have the following input.

#                         ⇓⇓⇓
extensions = [[1, 2], [3, [4]]]

List.flatten(extensions)
#⇒ [1, 2, 3, 4]

extensions |> :lists.reverse() |> Enum.reduce(&++/2)
#⇒ [1, 2, 3, [4]]

Upvotes: 3

Daniel
Daniel

Reputation: 2554

You can use List.flatten/1:

iex> List.flatten(extensions)
[
  %{extension: "zip", size: 3627, type: "archives"},
  %{extension: "xml", size: 3627, type: "documents"},
  %{extension: "png", size: 458605, type: "graphics"},
  %{extension: "png", size: 458605, type: "graphics"}
]

Upvotes: 4

Related Questions