TheSquad
TheSquad

Reputation: 7506

Elixir Enum.sort not sorting correctly

I'm having some issues trying to sort a list of structs in Elixir...

I can't find out what I'm doing wrong.

IO.puts "########### MY TOP 5 #############"
IO.inspect mytop5
IO.puts "=================================" 
sorted = Enum.sort_by(mytop5, &(&1.count))
IO.inspect sorted
IO.puts "------------------------"

Here's the result

iex(67)> ########### MY TOP 5 #############
iex(67)> [%{count: "3", from: "AUD", rate: 0.64536947, to: "EUR"},
%{count: "10", from: "USD", rate: 1.3876, to: "AUD"},
%{count: "11", from: "USD", rate: 0.89726335, to: "EUR"}]
iex(67)> =================================
iex(67)> [%{count: "3", from: "AUD", rate: 0.64536947, to: "EUR"},
%{count: "11", from: "USD", rate: 0.89726335, to: "EUR"},
%{count: "10", from: "USD", rate: 1.3876, to: "AUD"}]
iex(67)> ------------------------

while :

iex(3)> [%{plop: "aze", count: 5, name: "a"}, %{plop: "aze", count: 1, name: "p"}, %{plop: "aze", count: 45, name: "e"}] |> Enum.sort_by(&(&1.count))
[%{count: 1, name: "p", plop: "aze"}, %{count: 5, name: "a", plop: "aze"},
 %{count: 45, name: "e", plop: "aze"}]

Upvotes: 0

Views: 686

Answers (1)

Gazler
Gazler

Reputation: 84180

This is sorting based on count being a string:

Enum.sort(["3", "10", "5"])# ["10", "3", "5"]
Enum.sort([3, 10, 5])      # [3, 5, 10]

This is because "10" < "3" is true due to the first character:

Enum.sort(["30", "9", "10", "1", "100", "3"])
# ["1", "10", "100", "3", "30", "9"]

You can use String.to_integer/1 to convert it:

Enum.sort_by(mytop5, &(String.to_integer(&1.count)))

Upvotes: 5

Related Questions