listelixirflatten

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.


Solution

  • 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]]