josefrichter

josefrichter

Optimize function: find and update/replace in list of maps

I have this list of maps (or structs) and I get a list of newly updated maps. I want to update the maps in the old list with the values from the new list. Basically I can just replace the old ones with the new ones (in my real code it’s all structs rather than maps).

This is what I came up with:

olds = [
  %{class_id: 1, user_id: 1},
  %{class_id: 1, user_id: 2},
  %{class_id: 1, user_id: 3},
  %{class_id: 1, user_id: 4},
  %{class_id: 1, user_id: 5}
]

news = [
  %{class_id: 1, user_id: 2, new_key: 123},
  %{class_id: 1, user_id: 4, new_key: 456, another_new_key: 789}
]

# expected output
# [
#   %{class_id: 1, user_id: 1},
#   %{class_id: 1, user_id: 2, new_key: 123},
#   %{class_id: 1, user_id: 3},
#   %{class_id: 1, user_id: 4, new_key: 456, another_new_key: 789},
#   %{class_id: 1, user_id: 5}
# ]

olds |> Enum.map(fn old ->
  new_with_same_ids = news |> Enum.find(fn new -> new.class_id == old.class_id and new.user_id == old.user_id end)
  if (new_with_same_ids != nil) do
    new_with_same_ids
  else
    old
  end
end)
|> IO.inspect

This works, but not sure it’s very efficient, as it probably traverses both lists in m*n fashion I guess.

My second attempt is much simpler:

news ++ olds |> Enum.uniq_by(fn el -> {el.class_id, el.user_id} end) |> Enum.sort_by(& &1.user_id)
|> IO.inspect

But I lose the original order and have to use sort_by

Any suggestions how to do this more efficiently, please?

Thank you very much.

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe
news_by_id = Map.new(news, &{&1.user_id, &1})

Enum.map(olds, fn old -> Map.get(news_by_id, old.user_id, old) end)

The thought process here is basically: You only need the news sometimes, whereas you always need the olds, and you want them in that order. So make a map of the news for efficient lookup, then traverse the olds and either use the new if it exists, or use the old. Map.get/3 is used with the 3rd arg as the default to just succinctly default to the old instead of having to write out a case do ourselves.

EDIT: if news can contain entirely new entities then you’ll need to do more.

Also Liked

josefrichter

josefrichter

no, no, yes :slightly_smiling_face:

In my real code these are in fact structs where user_id and class_id together constitute a composite primary key.

One twist I can think of is old containing some keys not present in new, so I’d need to update the old map with new keys, rather than just replace the whole map. But I don’t need that for now.

stefanluptak

stefanluptak

Ok, hard to beat @benwilson512’s solution then. :slight_smile:

josefrichter

josefrichter

thank you, that works nicely! according to benchmarks it’s the fastest one.

Where Next?

Popular in Questions Top

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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
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
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
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
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
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
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
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement