31

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 3

78

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)
4
  • Ahhh, nice. Tried something like List.delete. Filter, thanks. Solution was data = Enum.filter(data, & !is_nil(&1))
    – Sardoan
    Commented Sep 21, 2017 at 9:17
  • False is not included, so I need only to check for nil. Your solution works perfect. Thanks again :) I make a query before for the last changes in the databse. With a new databse I got some nils and had to remove them.
    – Sardoan
    Commented Sep 21, 2017 at 9:25
  • 24
    Also: Enum.reject(list, &is_nil/1).
    – Dogbert
    Commented Sep 21, 2017 at 10:00
  • 1
    Enum.reject(list, &is_nil/1) is particularly elegant—nice solution
    – sambecker
    Commented Aug 25, 2018 at 21:35
0

this worked for me :

Enum.filter(s, fn x -> if(x != "") do x end end)
0
Enum.filter(list, fn x -> x != "" end)
1
  • 1
    Hi! Please edit your answer to expand a little bit upon how the code snippet you posted works. Thanks!
    – Julia
    Commented Mar 5, 2021 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.