thojanssens1
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.
Marked As Solved
hauleth
I cannot find docs to back it up, but I believe that you want Enum.sort_by(list, &{&1.color, &1.name}).
Also Liked
LostKobrakai
Tuples are ordered by size, two tuples with the same size are compared element by element.
sodapopcan
lud
No, this will sort that list: [{false, false},{false, false},{false, false},{false, false}].
You can just reverse the list. If you want to sort by ascending name but descending color you will have to compute a score or something like that, like mapping colors to integers and multiply them by -1 to get descending order.
Last Post!
LostKobrakai
At that point I think it makes sense to use a custom compare function, instead of trying to come up with some intermediary, which happens to be sorted correctly without one.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









