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

how to sort tuple list by first element, third element, then second element?

The data is:

[{{0, 0, 0}, 0}, {{0, 3, 6}, 0}, {{0, 3, 9}, 0}, {{0, 4, 6}, 0}]

I want to transform it to as follows, How to write the sort condition?

[{{0, 0, 0}, 0}, {{0, 3, 6}, 0}, {{0, 4, 6}, 0}, {{0, 3, 9}, 0}]

My writen code is not work.

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

b = Enum.sort(
 a,
 fn {{x, y, z}, _}, {{x1, y1, z1}, _} -> x > x1 and z > z1 and y > y1 end)

>Solution :

Enum.sort_by/2 is your friend.

[{{0, 0, 0}, 0},
 {{0, 3, 6}, 0},
 {{0, 3, 9}, 0},
 {{0, 4, 6}, 0}]
|> Enum.sort_by(fn {{x, y, z}, _} -> {x, z, y} end)
#⇒ [{{0, 0, 0}, 0},
#   {{0, 3, 6}, 0},
#   {{0, 4, 6}, 0},
#   {{0, 3, 9}, 0}]

Enum.sort/2 would be slightly slower, but it’s also usable with

|> Enum.sort(fn
  {{x1, y1, z1}, _}, {{x2, y2, z2}, _} ->
    {x1, z1, y1} <= {x2, z2, y2}
end)

Tuples are compared by elements, from left to right.

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