Elixir: Splitting a List in Two Sublists

This one’s going to be really quick:

We have a list and we want to split it into 2 sublists based on some condition, to work on each of them separately. That’s what we have Enum.split_with/2 for:

iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
{[4, 2, 0], [5, 3, 1]}

It’s not often that you might need this, but it’s good to keep in mind that there is a function for such a thing and you don’t have to reinvent the wheel.

Alexandra Docolin

Developer. React-Native worshipper. Please don't ask me about tests 😊

Tags
Elixir