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?
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.
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).
@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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With