Today I Learned

hashrocket A Hashrocket project

Using Enum Sort with multiple keys

You can sort an enum by multiple keys at once. For example, If we wanted to sort a list of 'Vehicle' structs by type and model at the same time, we could do this:

vehicle_list = [
  %Vehicle{type: "van", model: "Odyssey"},
  %Vehicle{type: "truck", model: "Avalanche"},
  %Vehicle{type: "van", model: "Pacifica"},
  %Vehicle{type: "truck", model: "Bronco"}
]

Enum.sort_by(vehicle_list, &{&1.type, &1.model})
#=>
[
  %Vehicle{type: "truck", model: "Avalanche"},
  %Vehicle{type: "truck", model: "Bronco"},
  %Vehicle{type: "van", model: "Odyssey"},
  %Vehicle{type: "van", model: "Pacifica"},
]

sort_by is first sorting the vehicles by the :type key and then sorting by the :model key.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.