ahmed-el-awad
ahmed-el-awad

Reputation: 53

Flatten one depth of list

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

Answers (3)

Alexey Pavlinov
Alexey Pavlinov

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

Peaceful James
Peaceful James

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

Aleksei Matiushkin
Aleksei Matiushkin

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

Related Questions