Anko

Anko

Just wondered if there is some standard library function for converting a map to a keyword list, but sorting it on the way.

something like;

map = %{"z" => 4, "y" => 6, "x" => 7}
order = ["x", "y"]
output = new_func(map, order)
# output now equals [{"x", 7}, {"y", 6}]

Showing Posts 1 to 10

codeanpeace

codeanpeace

Here’s one approach:

iex(1)> map = %{"z" => 4, "y" => 6, "x" => 7}
%{"x" => 7, "y" => 6, "z" => 4}
iex(2)> order = ["x", "y"]
["x", "y"]
iex(3)> Enum.map(order, fn key -> {key, Map.get(map, key)} end)
[{"x", 7}, {"y", 6}]
dimitarvp

dimitarvp

No the stdlib does not have that and you’ll see exactly why: it’s easy to do it yourself.

%{"z" => 4, "y" => 6, "x" => 7}
|> Map.take(["x", "y"])   # only take keys "x" and "y"
|> Map.to_list()          # convert the map to a list of tuples
|> Enum.sort_by(fn {key, _value} -> key end) # sort the list of tuples by their first element

And you will get [{"x", 7}, {"y", 6}] as your result.

cmo

cmo

You don’t need to convert the map to a list because maps are enumerable.

adamu

adamu

I said something similar 3 years ago :old_man: (actually @mudasobwa said it and I got the points. Thanks :chart_increasing::sparkles:).

dimitarvp

dimitarvp

I keep forgetting. :smiley:

Anko

Anko OP

I just like convenience functions, like how a map has keys() and values() when you could implement them yourself

dimitarvp

dimitarvp

Sure, you can just put it in your project. Two minute job.

dimitarvp

dimitarvp

That’s super inefficient though. If you had e.g. a map with 20 elements and wanted 10 of them, that solution in SO would do 10 map lookups.

Saving a line or two of code just to make the complexity of the code something almost O(n^2) is a bad practice. Whereas the Map.take + Enum.sort_by is not even two full passes of the underlying list.

cmo

cmo

You sure about that?

sort_by/3 calculates the comparison value for each element in the enumerable once instead of once for each element in each comparison. This implies sort_by/3 must do an initial pass on the data to compute those values.

However, if those values are cheap to compute, for example, you have already extracted the field you want to sort by into a tuple, then those extra passes become overhead. In such cases, consider using List.keysort/3 instead

dimitarvp

dimitarvp

Well I am not in the mood to compose a benchmark project but if you want to, go crazy.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews