Reputation: 672
Given a map, I want to sort the key-value pairs in a given order which I will provide via a list of all keys. Since maps are unordered collections I replaced the map with a keyword list. But now I'm struggling with sorting all its entries according to the given list of keys. If anyone knows solution to this problem in elixir please let me know. Thanks in advance.
Upvotes: 0
Views: 1077
Reputation: 23119
You can use Enum.map/2
to map the sorted list of keys to the corresponding key-value pairs from your map:
ordered_keys = [:a, :b, :c]
map = %{
a: 1,
b: 2,
c: 3
}
Enum.map(ordered_keys, &{&1, map[&1]})
Output:
[a: 1, b: 2, c: 3]
If you prefer, you can also use a comprehension:
for key <- ordered_keys, do: {key, map[key]}
Upvotes: 4