Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sort a list of maps according to a list elixir

I have this sorted list

@days ["mon", "tue", "wen", "thu", "fri", "sat", "sun"]

and I have a list of maps such as

[%{day: "sat"}, %{day: "tue"}, %{day: "fri"}]

I am trying to sort the list of maps according to days, I have tried Enum.sort_by/2 but I am unable to put the right condition. any help would be thankful.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you want, is to produce a sorter with O(1) access in the first place

iex|💧|1 ▸ days = ["mon", "tue", "wen", "thu", "fri", "sat", "sun"]
["mon", "tue", "wen", "thu", "fri", "sat", "sun"]
iex|💧|2 ▸ days_idx = days |> Enum.zip(1..7) |> Map.new()

Now sorting the original list would be as easy as

iex|💧|3 ▸ Enum.sort_by(
...|💧|3 ▸   [%{day: "sat"}, %{day: "tue"}, %{day: "fri"}],
...|💧|3 ▸   &days_idx[&1[:day]])

#⇒ [%{day: "tue"}, %{day: "fri"}, %{day: "sat"}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading