Reputation: 53
I have a list nested inside another with a depth of 3.
[
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]]
]
After using List.flatten/1
my result is
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
I want to flatten it in the same way below, while still keeping the same order of the elements inside intact.
[
[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]
]
I wanted to know if there's a way to do that using any of Elixir's defined functions, I looked up the Elixir docs but wasn't able to find a way to do that without flattening the entire list.
Upvotes: 1
Views: 125
Reputation: 1
You also can use Enum.flat_map/1
iex> [
...> [[1, 2, 3], [4, 5, 6]],
...> [[1, 2, 3], [4, 5, 6]]
...> ] |> Enum.flat_map(fn x -> x end)
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]
Upvotes: 0
Reputation: 2233
Just use Enum.concat/1
:
Enum.concat([
[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]]
])
returns
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]
Upvotes: 4
Reputation: 121010
For the sake of completeness, here is another solution.
iex|🌢|1 ▶ Enum.reduce(input, &++/2)
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]
Upvotes: 0