Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir remove nil from list

Tags:

list

elixir

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.

like image 423
Sardoan Avatar asked Sep 21 '17 09:09

Sardoan


1 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) 
like image 188
Aleksei Matiushkin Avatar answered Sep 16 '22 18:09

Aleksei Matiushkin