Sardoan
Sardoan

Reputation: 817

Elixir remove nil from list

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.

Upvotes: 32

Views: 26632

Answers (3)

Enum.filter(list, fn x -> x != "" end)

Upvotes: 0

Fer
Fer

Reputation: 9

this worked for me :

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

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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)

Upvotes: 80

Related Questions