160 words, 1 min read

In our previous post, we sorted JavaScript objects by a custom order using a rank map. Elixir can do the sameβ€”just as cleanly.

Let’s say you have a list of maps representing issues:

tickets = [
%{type: :medium, title: "Scrollbar jitter"},
%{type: :critical, title: "Data loss on save"},
%{type: :low, title: "Typo in footer"},
%{type: :high, title: "Broken login link"}
]

And you want them sorted as: :critical β†’ :high β†’ :medium β†’ :low.

First, we define a rank map

severity_rank = %{
critical: 0,
high: 1,
medium: 2,
low: 3
}

This can then be used to sort using Enum.sort_by:

Enum.sort_by(tickets, fn ticket ->
Map.get(severity_rank, ticket.type, :infinity)
end)

Unknown types (e.g., typos or missing values) will land at the end thanks to :infinity.

If you'd rather fail fast on unknown types:

Enum.sort_by(tickets, fn ticket ->
Map.fetch!(severity_rank, ticket.type)
end)

If you use the same order across modules:

@severity_rank %{critical: 0, high: 1, medium: 2, low: 3}

Then:

Enum.sort_by(tickets, &Map.fetch!(@severity_rank, &1.type))