Skip to content

Instantly share code, notes, and snippets.

@Miserlou
Last active May 12, 2022 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Miserlou/14cf0681f21a72a7f874bb58b2303a32 to your computer and use it in GitHub Desktop.
Save Miserlou/14cf0681f21a72a7f874bb58b2303a32 to your computer and use it in GitHub Desktop.
How to Sort a Map By Value In Elixir
# I couldn't find this easily in the documentation or on Google.
# Here's how you sort a map in Elixir.
# Maps aren't a sorted structure, so the result is a keyword list.
input = %{
player_1: %{score: 2},
player_2: %{score: 1},
player_3: %{score: 10}
player_4: %{score: 5}
}
# sort_by is ascending by default
#[
# player_2: %{score: 1},
# player_1: %{score: 2},
# player_4: %{score: 5},
# player_3: %{score: 10}
#]
Enum.sort_by(input, fn {_k, v} -> v.score end)
# use :desc to reverse
#[
# player_3: %{score: 10},
# player_4: %{score: 5},
# player_1: %{score: 2},
# player_2: %{score: 1}
#]
Enum.sort_by(input, fn {_k, v} -> v.score end, :desc)
# Easy peasy!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment