thojanssens1

thojanssens1

Sort by multiple values?

Is there an easy way to sort a list of maps by some key, but if those keys are equal, be able to specify another key (and again if equal, another key, and so on)?

E.g.

fruits =
  [
    %{
      color: "yellow",
      name: "potato"
    },
    %{
      color: "red",
      name: "raspberry"
    },
    %{
      color: "red",
      name: "radish"
    },
    %{
      color: "yellow",
      name: "pineapple"
    },
  ]

First sort the maps by color ascending, but if equal, by name ascending.

Marked As Solved

hauleth

hauleth

I cannot find docs to back it up, but I believe that you want Enum.sort_by(list, &{&1.color, &1.name}).

17
Post #2

Also Liked

LostKobrakai

LostKobrakai

Tuples are ordered by size, two tuples with the same size are compared element by element.

https://erlang.org/doc/reference_manual/expressions.html#term-comparisons

sodapopcan

sodapopcan

You negate the terms:

Enum.sort_by(list, &{!&1.color, !&1.name})

lud

lud

No, this will sort that list: [{false, false},{false, false},{false, false},{false, false}].

You can just reverse the list. If you want to sort by ascending name but descending color you will have to compute a score or something like that, like mapping colors to integers and multiply them by -1 to get descending order.

al2o3cr

al2o3cr

sort_by is stable if EVERYTHING returns the same value:

iex(1)> [%{color: "yellow", name: "potato"}, %{color: "red", name: "apple"}] |> Enum.reverse() |> Enum.sort_by(&{!&1.color, !&1.name})

[%{color: "red", name: "apple"}, %{color: "yellow", name: "potato"}]

This should have returned the map with “yellow” first (like in your second example) if it was meaningfully sorting.

LostKobrakai

LostKobrakai

At that point I think it makes sense to use a custom compare function, instead of trying to come up with some intermediary, which happens to be sorted correctly without one.

Where Next?

Popular in Questions Top

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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
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

Other popular topics Top

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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
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
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
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement