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

Advertisements

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.

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.

Leave a ReplyCancel reply