Iterate through map of dynamic keys and update their values

I have some code like this

    groups = [
      %{1 => 19, 2 => 20},
      %{6 => 18},
      %{3 => 15},
      %{4 => 11}
    ]

    result = BalanceLib.standardise_groups(groups)

I want to iterate through this list and change every value to it’s old value + 1. I wrote this

  def standardise_groups(groups) do
    groups
    |> Enum.map(fn group ->
      # Iterate over our map
      {_ignored, better_map} =
        Enum.map_reduce(group, %{}, fn {key, value}, acc ->
          result = Map.put(acc, key, value + 1)
          {nil, result}
        end)

      better_map
    end)
  end

But I’m wondering if Enum.map_reduce is a bad way of doing this. Is this the correct way or is there a better way?

Something like Enum.map(groups, fn group -> Map.new(group, fn {k, v} -> {k, v + 1} end) end) should be enough, but I am on mobile atm…

Note that if your way works is may not be better but it is correct.

(edit: fixed v +1 to v + 1)

1 Like

I created an example here to test:

defmodule BalanceLib do
 def standardise_groups(groups) do
   Enum.map(groups, fn group ->
     Map.new(group, fn {key, value} ->
       {key, value + 1}
     end)
   end)
 end
end

# Test data
groups = [
 %{1 => 19, 2 => 20},
 %{6 => 18},
 %{3 => 15},
 %{4 => 11}
]

# Call the function
result = BalanceLib.standardise_groups(groups)

# Output the result
IO.inspect(result)

1 Like

A useful thing when you have a Map and want a Map with different values (or keys) is Map.new:

iex(1)> %{1 => 10, 2 => 34} |> Map.new(fn {k, v} -> {k, v + 1} end)

%{1 => 11, 2 => 35}

That would let you replace the map_reduce in your example.

3 Likes