Need help with custom sorter

Hi,

I have a list of projects and I want to sort them in the specific way.

projects = 
[
%{name: "Project 1", status: "active"},
%{name: "Project 2", status: "canceled"},
%{name: "Project 3", status: "active"},
%{name: "Project 4", status: "draft"},
%{name: "Project 5", status: "draft"},
%{name: "Project 6", status: "active"},
%{name: "Project 7", status: "canceled"},
%{name: "Project 8", status: "draft"}
]

I want to sort projects by status so the first come active projects, then drafts and then canceled projects.

projects = 
[
%{name: "Project 1", status: "active"},
%{name: "Project 3", status: "active"}
%{name: "Project 6", status: "active"},
%{name: "Project 4", status: "draft"},
%{name: "Project 5", status: "draft"},
%{name: "Project 8", status: "draft"},
%{name: "Project 2", status: "canceled"},
%{name: "Project 7", status: "canceled"}
]

I should probably use Enum.sort_by function but I struggle with it a little bit. Can anyone help me with this?

Like this:

projects
|> Enum.sort_by(fn
  %{status: "active"} -> 0
  %{status: "draft"} -> 1
  %{status: "canceled"} -> 2
end)
7 Likes