Eduardo Pereira
Eduardo Pereira

Reputation: 870

Removing elements that have consecutive dupes in Elixir list

I have a list of numbers in Elixir, and I want to remove the duplicates, but only for the consecutive dupes.

For the following input list: [1,1,2,2,1,1,1,1,3,3,2,2].

The result should be: [1,2,1,3,2].

Upvotes: 0

Views: 722

Answers (1)

Dogbert
Dogbert

Reputation: 222118

Enum.dedup/1 does exactly what you want: it replaces consecutive duplicate elements with only one instance of it and returns the remaining elements in a list.

iex(1)> Enum.dedup([1, 1, 2, 2, 1, 1, 1, 1, 3, 3, 2, 2])
[1, 2, 1, 3, 2]

This works on all values that compare equal with ===, including maps:

iex(2)> Enum.dedup([%{a: 1}, %{a: 2}, %{a: 2}, %{a: 2}])
[%{a: 1}, %{a: 2}]

Upvotes: 4

Related Questions