Logo

Programming-Idioms

History of Idiom 113 > diff from v24 to v25

Edit summary for version 25 by lirossarvet:
[Elixir] formatting looked off

Version 24

2019-09-26, 18:43:18

Version 25

2019-09-26, 18:44:10

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Extra Keywords
traverse traversal
Extra Keywords
traverse traversal
Code
map 
|> Map.to_list 
|> Enum.sort(fn ({_k1, val1}, {_k2, val2}) -> val1 <= val2 end) |> Enum.each(fn ({k, v}) -> IO.puts("#{k}: #{v}") end)
Code
map 
|> Map.to_list 
|> Enum.sort(fn ({_k1, val1}, {_k2, val2}) -> val1 <= val2 end)
|> Enum.each(fn ({k, v}) -> IO.puts("#{k}: #{v}") end)
Comments bubble
We need to convert our map to a list to sort it. When converted, the list is a set of two element tuples which we can sort based on the last value. Finally we just want to iterate over those sorted tuples.
Comments bubble
We need to convert our map to a list to sort it. When converted, the list is a set of two element tuples which we can sort based on the last value. Finally we just want to iterate over those sorted tuples.
Doc URL
https://hexdocs.pm/elixir/Enum.html#sort/2
Doc URL
https://hexdocs.pm/elixir/Enum.html#sort/2