nachoelchido
nachoelchido

Reputation: 139

How to delete "any" element of a list in elixir

I have a list of lists

>> list = [[1,""],[2,"b"],[3,""],[4,"c"]]

I want to delete the lists that contains "" element

>>list = [[2,"b"],[4,"c"]]

I'm trying to find something like

list = List.delete(list,[any,""])

Upvotes: 1

Views: 4381

Answers (1)

Brett Beatty
Brett Beatty

Reputation: 5973

You could combine Enum.reject/2 with Enum.member?/2 and reject any list that contains empty string

iex> Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], &Enum.member?(&1, ""))
[[2, "b"], [4, "c"]]

If your inner lists are always the same two-item style and you're only wanting to check the second item, you could also use an anonymous function

iex> Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], fn [_, b] -> b == "" end)
[[2, "b"], [4, "c"]]

or a comprehension that does pretty much the same thing

iex> for [a, b] when b != "" <- [[1,""],[2,"b"],[3,""],[4,"c"]], do: [a, b]
[[2, "b"], [4, "c"]]

Upvotes: 6

Related Questions