fireproofsocks
Enum.sort_by to sort a record set (i.e. a list of maps) based on 2 "columns"
I found José’s useful response to how to sort a list of maps by a column. I’m not following how to expand this into sorting by multiple columns.
For example, given the following “record set”:
records = [
%{age: 6, name: "Apple"},
%{age: 4, name: "Boy"},
%{age: 1, name: "Cat"},
%{age: 0, name: "Dog"}
]
I can sort by age descending doing something like this:
Enum.sort_by(records, fn(r) -> r[:age] end, &>=/2)
However, what if I want to sort by :name when there is a tie? Something like how a SQL query would do ORDER BY age DESC, name ASC.
Thanks for any pointers!
Marked As Solved
peerreynders
Interactive Elixir (1.9.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> data = [
...(1)> %{age: 6, name: "Apple"},
...(1)> %{age: 4, name: "Dog"},
...(1)> %{age: 1, name: "Cat"},
...(1)> %{age: 4, name: "Boy"}
...(1)> ]
[
%{age: 6, name: "Apple"},
%{age: 4, name: "Dog"},
%{age: 1, name: "Cat"},
%{age: 4, name: "Boy"}
]
iex(2)> compare =
...(2)> fn
...(2)> x, x -> :eq
...(2)> x, y when x > y -> :gt
...(2)> _, _ -> :lt
...(2)> end
#Function<13.126501267/2 in :erl_eval.expr/5>
iex(3)> age_desc =
...(3)> fn lhs, rhs ->
...(3)> case compare.(lhs[:age], rhs[:age]) do
...(3)> :lt -> false
...(3)> _ -> true
...(3)> end
...(3)> end
#Function<13.126501267/2 in :erl_eval.expr/5>
iex(4)> Enum.sort(data, age_desc)
[
%{age: 6, name: "Apple"},
%{age: 4, name: "Dog"},
%{age: 4, name: "Boy"},
%{age: 1, name: "Cat"}
]
iex(5)> age_desc_name_asc =
...(5)> fn lhs, rhs ->
...(5)> case {compare.(lhs[:age],rhs[:age]), compare.(lhs[:name],rhs[:name])} do
...(5)> {:lt, _} -> false
...(5)> {:eq, :gt} -> false
...(5)> {_,_} -> true
...(5)> end
...(5)> end
#Function<13.126501267/2 in :erl_eval.expr/5>
iex(6)> Enum.sort(data, age_desc_name_asc)
[
%{age: 6, name: "Apple"},
%{age: 4, name: "Boy"},
%{age: 4, name: "Dog"},
%{age: 1, name: "Cat"}
]
iex(7)>
8
Also Liked
benwilson512
Author of Craft GraphQL APIs in Elixir with Absinthe
Enum.sort_by(records, fn(r) -> {r[:age], r[:name]} end, &>=/2)
Tuples, when compared with one another, are ordered according to what appears first in the tuple. So in this case it would sort by age first, then by name. Doing it by different directions for each though is a bit harder.
3
fireproofsocks
Wow, that is crazy thorough. Thank you for the example!
1
Popular in Questions
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Hi,
I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
Hi everyone!
I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir
iex(2)...
New
Other popular topics
What is the proper way to load a module from a file in to IEX?
In the python world, doing something like this pretty standard:
from ....
New
Hello!
tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability.
After spen...
New
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service.
Currently when I de...
New
Using vs code and installed ElixirLS: support and debugger.
And I got an error popped up on start up says
Failed to run ‘elixir’ comma...
New
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Hi all,
I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage.
I'm trying to use Postg...
New
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum.
...
New
Hi everyone!
I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New








