Ashish Sharma
Ashish Sharma

Reputation: 672

How to get ordered key-value pairs from a map, given an ordered list of keys?

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

Answers (2)

Adam Millerchip
Adam Millerchip

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

potibas
potibas

Reputation: 627

This should work...

Enum.sort(keyword_list, fn {k, _v} -> k end)

Upvotes: 0

Related Questions