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.

cmo

cmo

If you need sorted keys then a Map is the wrong data structure. There are lists, keyword lists, records, custom data structures, etc.

Search for “map with ordered keys” as this has been discussed on here a few times.

NobbZ

NobbZ

Sounds like presentation layer…

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
Harrisonl
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
LegitStack
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
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

Other popular topics Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
New
quazar
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
minhajuddin
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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

We're in Beta

About us Mission Statement