Reputation: 353
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
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
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