Remove complete object from the list if valu is duplicate

Here i am having a list like this:

[%{"countryCode" => "IN", "name" => "ABCD", "phone" => "7878898972"}, %{"countryCode" => "IN", "name" => "EFGH", "phone" => "7878898972"}, %{"countryCode" => "IN", "name" => "IJKL", "phone" => "6578898971"}]

Inside list there are three objects but in first two phone values are same. so i have to eliminate one complete object from that list. How can I achieve that in a simple way?

Note: Logic should work on all types of list having key value duplicate.

Thank You.

You can reduce the list over 2-tuple accumulator that re-builds the list and keeps track of the phone numbers you’ve already seen in a MapSet. If the list item’s number is already in the set of seen phone numbers, you don’t add it to the list.

Can look at Enum.uniq_by/2.

Would be something like:

my_list = [
  %{"countryCode" => "IN", "name" => "ABCD", "phone" => "7878898972"}, 
  %{"countryCode" => "IN", "name" => "EFGH", "phone" => "7878898972"}, 
  %{"countryCode" => "IN", "name" => "IJKL", "phone" => "6578898971"}

Enum.uniq_by(my_list, & &1["phone"])

# Result
  %{"countryCode" => "IN", "name" => "ABCD", "phone" => "7878898972"},
  %{"countryCode" => "IN", "name" => "IJKL", "phone" => "6578898971"}

You haven’t said which object must be kept when there are duplicates – the first one?

What does that even mean? Sounds too generic.

1 Like