Logo

Programming-Idioms

History of Idiom 113 > diff from v23 to v24

Edit summary for version 24 by lirossarvet:
New Elixir implementation by user [lirossarvet]

Version 23

2019-09-26, 18:11:45

Version 24

2019-09-26, 18:43:18

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)
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