I know I can split an even list in two equal halves in elixir by doing this:
list = [1, 2, 3, 4, 5, 6]
len = length(list)/2 |> round
[a, b] = Enum.chunk(list, len) # => [[1, 2, 3], [4, 5, 6]]
but is there a ruby-esque method built-in or some more efficient way of doing this that also handles odd-length lists?
Enum.chunk actually takes 4 arguments and will work with an odd length list if you include the 4th (pad
) argument:
iex(14)> Enum.chunk([1,2,3,4,5], 3, 3, [])
[[1, 2, 3], [4, 5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With