kamaroly

kamaroly

How to Control Map Key Order in Elixir for Custom Report Formatting?

Elixir is sorting map by key name in ascending order, but I don’t want this behaviour. It is causing me to have undesired reports output. I’d like to have the employee number and names to begin, then followed by leave types instead of the following.

Is there a way to rearrange the map by key in Elixir, so that

records = [
  %{
    "Annual Leave" => "0",
    "Compassionate" => "0",
    "Maternity" => "0",
    "Paternity" => "0",
    "Paternity Leave" => "0",
    "Sick Leave" => 0,
    "Study Leave" => 0,
    "emp_no" => "EMP0004",
    "names" => "Benard Kipucho"
  },
  %{
    "Annual Leave" => "87",
    "Compassionate" => 0,
    "Maternity" => 0,
    "Paternity" => 0,
    "Paternity Leave" => "1024",
    "Sick Leave" => "100",
    "Study Leave" => "989",
    "emp_no" => "EMP001",
    "names" => "Kamaro Lambert"
  }
]

# SOMETHING LIKE THIS CAN make the map starts with emp_no and names.
Enum.map_key_starts_with(records, ["emp_no", "names"])

The above should give the following results

[
  %{
    
    "emp_no" => "EMP0004", # Shifted to the starting point
    "names" => "Benard Kipucho", # Shifted to the starting point
    "Annual Leave" => "0",
    "Compassionate" => "0",
    "Maternity" => "0",
    "Paternity" => "0",
    "Paternity Leave" => "0",
    "Sick Leave" => 0,
    "Study Leave" => 0
  },
  %{
    "emp_no" => "EMP001", # Shifted to the starting point
    "names" => "Kamaro Lambert",# Shifted to the starting point
    "Annual Leave" => "87",
    "Compassionate" => 0,
    "Maternity" => 0,
    "Paternity" => 0,
    "Paternity Leave" => "1024",
    "Sick Leave" => "100",
    "Study Leave" => "989"
  }
]

Marked As Solved

kamaroly

kamaroly

Thank you all for jumping on this issue. I truly appreciate.

I had to write a Report module that:

  1. Aceepts a list of records, and a list of keys in order I want.
  2. Loops throuch each record and map it with Map.get(record, ordered_key, "")
 records = [
     %{
     "Annual Leave" => Decimal.new("21"),
     "Compassionate" => Decimal.new("14"),
     "emp_no" => "EMP001",
     "names" => "Jane Doe"
     },
     %{
     "Annual Leave" => Decimal.new("10"),
     "Compassionate" => Decimal.new("5"),
     "emp_no" => "EMP002",
     "names" => "John Smith"
     }
]
Report.format(records, ["names", "emp_no", "Annual Leave", "Compassionate"])

Gives

 [
     %{
     "names" => "Jane Doe",
     "emp_no" => "EMP001",
     "Annual Leave" => 21,
     "Compassionate" => 14,

     },
     %{
     "names" => "John Smith",
     "emp_no" => "EMP002",
     "Annual Leave" => 10,
     "Compassionate" => 5,
     }
]

Also Liked

rvirding

rvirding

Creator of Erlang

To make matters worse (? :grinning:) the ordering of elements in maps is completely undefined and changes depending on the number of elements. It use to be that for less than 32 elements the ordering was term ordering and for more elements it was “random” depending on the internal search algorithm used.

The thing to remember is that the actual ordering is purely internal. There are iterator functions which can give you some control of which order you want to step over the elements.

LostKobrakai

LostKobrakai

Maps are an unordered dataformat. The BEAM just has a default sort order given it has a global ordering between any term it can represent, which is used to order things where they need to become ordered. So the solution here is to use a datatype which does retain order (lists) instead of maps.

For your usecase I’d even argue that this is a pure view layer concern – as in how data is presented – so your view layer code could simply order the columns as needed before rendering the data.

NobbZ

NobbZ

Have you considered using structs with a custom inspection protocol implementation?

Maps with string keys deep into the program always smell.

Where Next?

Popular in Questions Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
9mm
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
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement