Sort by multiple values?

Is there an easy way to sort a list of maps by some key, but if those keys are equal, be able to specify another key (and again if equal, another key, and so on)?

E.g.

fruits =
  [
    %{
      color: "yellow",
      name: "potato"
    },
    %{
      color: "red",
      name: "raspberry"
    },
    %{
      color: "red",
      name: "radish"
    },
    %{
      color: "yellow",
      name: "pineapple"
    },
  ]

First sort the maps by color ascending, but if equal, by name ascending.

I cannot find docs to back it up, but I believe that you want Enum.sort_by(list, &{&1.color, &1.name}).

9 Likes

Thanks @hauleth for all the help you provide :+1: :+1: :+1:

Tuples are ordered by size, two tuples with the same size are compared element by element.

https://erlang.org/doc/reference_manual/expressions.html#term-comparisons

4 Likes