Logo

Programming-Idioms

History of Idiom 28 > diff from v58 to v59

Edit summary for version 59 by programming-idioms.org:
[Erlang] Removed demo (not a demo)

Version 58

2020-04-29, 10:43:32

Version 59

2020-05-21, 20:22:59

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Variables
items,x,p
Imports
	
Imports
	
Code
sort_by_birth(ListOfMaps) ->
  lists:sort(
    fun(A, B) ->
      maps:get(birth, A, undefined) =< maps:get(birth, B, undefined)
    end, ListOfMaps).

sort_by_birth(ListOfRecords) -> lists:keysort(#item.birth, ListOfRecords).
Code
sort_by_birth(ListOfMaps) ->
  lists:sort(
    fun(A, B) ->
      maps:get(birth, A, undefined) =< maps:get(birth, B, undefined)
    end, ListOfMaps).

sort_by_birth(ListOfRecords) -> lists:keysort(#item.birth, ListOfRecords).
Comments bubble
First function works with a list of maps, like [#{birth => "1982-01-03"}, …].
Second function works with a list of records, like [#item{birth = "1982-01-03", …}, …]
Comments bubble
First function works with a list of maps, like [#{birth => "1982-01-03"}, …].
Second function works with a list of records, like [#item{birth = "1982-01-03", …}, …]
Doc URL
http://erldocs.com/current/stdlib/lists.html?i=5&search=lists#undefined
Doc URL
http://erldocs.com/current/stdlib/lists.html?i=5&search=lists#undefined
Demo URL
http://www.tryerlang.org/