Hey everyone!
How can I keep the original ordering of a Map?
I’ve created one and notice that after the creation, the order of elements altered in alfabetically. How can I keep them?
Hey everyone!
How can I keep the original ordering of a Map?
I’ve created one and notice that after the creation, the order of elements altered in alfabetically. How can I keep them?
You need to create your own struct and implement that on your own.
This post might help…
Then don’t use a map but a keyword list instead. Elixir’s stdlib supports it well, check the List
module in the docs.
If it’s just for your own pleasure in dev or when debugging, IO.inspect
and dbg
take options to allow this custom_options: [sort_maps: true]
. I feel like pretty: true
might do as well.
If you want to preserve the insertion order, you can check :aja
’s OrdMap
, which does exactly that, as well as offering good performance and implementing the Jason.Encoder
protocol amongst other things:
https://hexdocs.pm/aja/Aja.OrdMap.html
(disclaimer: I’m the author )
Nice