To solve your specific problem you might want to use the Enum.uniq_by/2 function
Enum.uniq_by(cards, & &1.batchId) # Remove duplicates
|> Enum.map(& %{BatchId: &1.batchId}) # Mapping into a new map with an capitalised key
In general you cannot return anything from Enum.each. You need to use Enum.map/2 for that.
Also you should move away from thinking that you can update variables outside of functions. You can’t and you therefor need to look into functional patterns like map & reduce to transform data. Please ask if you have any additional questions.