Getting rid of empty list inside list

Hello everyone. First off I want to thank everyone in the community! You guys are awesome and I am learning a lot about elixir through this community.

The question I have today is getting rid of empty list inside list. I tried Enum.filter but the values show up as nil.

    [],
  [],
  [
    %{
      "itemId" => 1038,
      "participantId" => 1,
      "timestamp" => 292190,
      "type" => "ITEM_PURCHASED"
    },
    %{
      "itemId" => 1001,
      "participantId" => 1,
      "timestamp" => 294368,
      "type" => "ITEM_PURCHASED"
    }
  ],
  [],
  [],

Cheers,

Niral Patel

What have you tried? Enum.filter shouldn’t introduce any values that haven’t been there before…

1 Like

This is the code which I tried with.
Enum.filter(rest, fn x -> x != [] end)

No nils for appearing for me:

iex(1)> rest = [[], [:a], [], [:b]]
[[], [:a], [], [:b]]
iex(2)> Enum.filter(rest, fn x -> x != [] end)
[[:a], [:b]]
2 Likes

Depending on your needs, you could also try List.flatten/1.

Your solution would not account for nested empty lists, which may be valid values?

4 Likes

All 3 are working for me:

  • Enum.filter(list, & &1 != [])
  • Enum.reject(list, & &1 == [])
  • Enum.reject(list, &Enum.empty?/1)

Proof

6 Likes

You three are completely right. What I did was Enum.map |> Enum.filter instead of Enum.filter first. Thank you guys and cheers :slight_smile:

2 Likes