like this:
list1 = [1,2,3,4,5]
list2 = [2,3,6]
list1 & list2 = [2,3]
I need to find the repeat list i.e. common items in list1
and list2
.
The function you are looking for is Set.intersection/2:
iex> Set.intersection(Enum.into([1, 2, 3 ,4 ,5], HashSet.new), Enum.into([2, 3, 6], HashSet.new))
[2, 3]
Please note that the conversion to a set means that duplicates are not permitted:
Enum.into([1, 2, 3 ,2 ,5, 3], HashSet.new)
HashSet<[2, 3, 1, 5]>
Also note that order is not maintained:
iex>Enum.into([1, 2, 3 ,4 ,5, 6], HashSet.new) |> Set.to_list
[2, 6, 3, 4, 1, 5]
Not sure if elixir has a similar &
operator for list
s.
But, you can achive your desried result by using the --
operator twice:
iex> list1
# => [1, 2, 3, 4, 5]
iex> list2
# => [2, 3, 6]
iex> list3 = list1 -- list2
# => [1, 4, 5]
iex> final_list = list1 -- list3
# => [2, 3] # this is your desired result
You can do it in one line too:
iex> list1 -- (list1 -- list2)
# => [2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With