Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort list of map by map value in Elixir?

Tags:

elixir

I need to sort list of map, using value of map.

list = [
  %{id: 3, name: "Abe", count: 50},
  %{id: 1, name: "Bill", count: 10},
  %{id: 2, name: "Candy", count: 2},
]

For example, I need that list sorted by id:

list = [
  %{id: 1, name: "Bill", count: 10},
  %{id: 2, name: "Candy", count: 2},
  %{id: 3, name: "Abe", count: 50},
]

...or by count or name. How I can do it?

like image 964
Dmitriy Makarenko Avatar asked Aug 09 '18 04:08

Dmitriy Makarenko


People also ask

How do you sort a list in Elixir?

To sort a list of strings alphabetically, you can just use Enum. sort/1 , which will order items by their default order (which is alphabetic ordering for strings). To sort a list by a different property, such as string length, you can use Enum. sort_by/2 , which takes a mapper function as second argument.

Are elixir maps ordered?

12.3) Maps are the "go to" key-value data structure in Elixir. Key-value pairs in a map do not follow any order (that's why the printed map in the example above has a different order than the map that was created).


2 Answers

@IgodDrozdov provided a good solution. A more basic one: you can use Enum.sort/2:

Enum.sort(list, &(&1.id < &2.id))

2nd argument must define a binary relation (like sorter in Enum.sort_by/3)

like image 80
Nathan Ripert Avatar answered Sep 17 '22 13:09

Nathan Ripert


There's Enum.sort_by function, which accepts list, mapper and sorter. The following code does the trick:

list = [
  %{id: 3, name: "Abe", count: 50},
  %{id: 1, name: "Bill", count: 10},
  %{id: 2, name: "Candy", count: 2},
]

Enum.sort_by list, &Map.fetch(&1, :id)

we need to provide list and a function which returns the attribute of mapping. Map.fetch(&1, :id) returns a value by key, or even simpler:

Enum.sort_by list, & &1.id

sorter by default is <=/2 function, which sorts the list in asc order.

like image 32
Igor Drozdov Avatar answered Sep 18 '22 13:09

Igor Drozdov