Elixir remove nil from list

Viewed 20257

I got the following structure:

[nil,
 %{attributes: %{updated_at: ~N[2017-09-21 08:34:11.899360]},
 ...]

I want to remove the nils. How do I do that? Tried Enum.reduce/3 but it didn't work.

3 Answers

Enum.filter/2 comes to the rescue:

Enum.filter(list, & !is_nil(&1))

If you are certain there could not be false atoms in the list (the other possible falsey value in Elixir,) the filter might be simplified to:

Enum.filter(list, & &1)

Also (credits to @Dogbert) there is a counterpart function Enum.reject/2 that “returns elements of enumerable for which the function fun returns false or nil.”

Enum.reject(list, &is_nil/1)

this worked for me :

Enum.filter(s, fn x -> if(x != "") do x end end)
Enum.filter(list, fn x -> x != "" end)
Related