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

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
Brian
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
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
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

Other popular topics Top

lanycrost
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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 th...
New
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
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement