grangerelixx
Enum.sort_by list of maps
I have a list of maps.
post_a =
%{
post_body_size: 4,
date: ~D[2021-06-05]
}
post_b =
%{
post_body_size: 4,
date: ~D[2021-06-04]
}
post_c =
%{
post_body_size: 4,
date: ~D[2021-06-03]
}
post_d =
%{
post_body_size: 5,
date: ~D[2021-06-02]
}
I am trying to organize the posts based on the body size (ascending order) and for cases when body sizes are same, the next sort_by is the date(descending order).
[post_count_1, post_count_2, post_count_3, post_count_4] =
[post_a, post_b, post_c, post_d]
|> Enum.sort_by(&{Map.fetch(&1, :post_body_size), {:desc, Map.fetch(&1, :date)}})
This doesn’t seem to sort the posts with (only) same body size according to date. Any inputs on how to resolve this or where I am possibly going wrong?
Most Liked
APB9785
In order to compare Date structs, you have to pass the Date module as the third argument to Enum.sort_by/3 as shown in the very last example from Enum - sort_by/3. But by doing this I’m not sure if you can do the Integer comparison for :post_body_size in the same function. Here’s a two-pass implementation:
post_list
|> Enum.sort_by(&Map.fetch!(&1, :date), {:desc, Date})
|> Enum.sort_by(&Map.fetch!(&1, :post_body_size))
grangerelixx
I am sorry, its working, I have been trying to assert with the wrong posts. Your solution works for both the cases. Thanks a lot!
grangerelixx
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
- #api
- #forms
- #metaprogramming
- #security
- #hex









