Last active
May 14, 2024 01:59
-
-
Save Miserlou/14cf0681f21a72a7f874bb58b2303a32 to your computer and use it in GitHub Desktop.
How to Sort a Map By Value In Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
commented
May 14, 2024
<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