Skip to content

Instantly share code, notes, and snippets.

@Miserlou
Last active May 14, 2024 01:59
Show Gist options
  • 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!
@KingGame0
Copy link

<style type="text/css"></style> KingGame -- Gold99 PGasia

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment