This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #28 Sort by a property
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
- Ada
- C
- Clojure
- C++
- C++
- C++
- C#
- C#
- D
- Dart
- Dart
- Elixir
- Erlang
- Go
- Go
- Go
- Groovy
- Groovy
- Haskell
- Haskell
- JS
- Java
- Java
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Scala
- Scheme
- Smalltalk
- VB
- VB
(sort-by :p items)
Clojure keywords also act as functions that look up the value of their key in associative data structures
std::sort(begin(items), end(items), [](const auto& a, const auto& b) { return a.p < b.p; });
This sort is not a stable sort.
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).
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", …}, …]
Second function works with a list of records, like [#item{birth = "1982-01-03", …}, …]
type ItemPSorter []Item
func (s ItemPSorter) Len() int{ return len(s) }
func (s ItemPSorter) Less(i,j int) bool{ return s[i].p<s[j].p }
func (s ItemPSorter) Swap(i,j int) { s[i],s[j] = s[j],s[i] }
func sortItems(items []Item){
sorter := ItemPSorter(items)
sort.Sort(sorter)
}
The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
items.sort(function(a,b) {
return compareFieldP(a.p, b.p);
});
Implements your own compareFieldP depending on the type of p.
Collections.sort(items, new Comparator<Item>(){
@Override
public int compare(Item a, Item b){
return a.p - b.p;
}
});
items is a List<Item>.
Use an anonymous class which implements Comparator<Item>.
Use an anonymous class which implements Comparator<Item>.
sort(items, comparing(x -> x.p));
Object array sort.
[items sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"p" ascending:YES]]]
Presumed the array contains any kind of objects with a property p (e.g., maps with key p, etc.) ObjC arrays very rarely contain structs; for such case a plain-C solution would be better, and of course possible
type
TItem = class p: Integer; end;
TItems = specialize TFPGObjectList<TItem>;
var items: TItems;
function compare(const a, b: TItem): Integer;
begin
Result := a.p - b.p;
end;
begin
items := TItems.Create;
// Add items here.
items.Sort(@compare);
end.
(define-struct item (p x y) #:transparent)
(define items (list (item 1 2 3) (item 0 0 0) (item 5 2 1)))
(sort items < #:key item-p)
< is the integer comparison function. There is also string<?.