Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Elixir how do you sort a keyword list by value?

I am trying to develop a simple POC in Elixir that requires information storage in a map. The problem is I cannot figure out how to display the map as list sorted by value.

defmodule MapUpdater do
    def update_score(map, player, :double), do: Map.update(map, player, 2, &(&1 * 2))
    def update_score(map, player, :halve), do: Map.update(map, player, .5, &(&1 * 0.5))
    def update_score(map, player, :penalize), do: Map.update(map, player, -1, &(&1 - 1))
    def view_scores(map, :top), do: Map.to_list(map) |> Enum.sort_by(???)
    def view_scores(map, :bottom), do: Map.to_list(map) |> Enum.sort_by(???)
end

I have tried:

Enum.sort_by(&(elem(&1, 1)) > &(elem(&2, 1)))

and any number of variations of this, but reading the Documentation over and over is not helping me. Any advice?

like image 409
smkarber Avatar asked Nov 21 '25 09:11

smkarber


1 Answers

Enum.sort_by/2 takes an arity one function that and sorts the input based on the value returned by calling the function on each element, so that should be |> Enum.sort_by(&(elem(&1, 1))).

iex(1)> list = [a: 1, b: 2, c: 0, d: 3, e: -1]
[a: 1, b: 2, c: 0, d: 3, e: -1]
iex(2)> list |> Enum.sort_by(&(elem(&1, 1)))
[e: -1, c: 0, a: 1, b: 2, d: 3]

There's also a much more elegant way to sort lists of tuples by the value of one of its element: List.keysort/2:

iex(3)> list |> List.keysort(1)
[e: -1, c: 0, a: 1, b: 2, d: 3]
like image 172
Dogbert Avatar answered Nov 23 '25 23:11

Dogbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!