Logo

Programming-Idioms

  • Elixir
  • Obj-c

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.

@import Foundation;
[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
Enum.sort_by(items, &(&1.p))
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

New implementation...
< >
programming-idioms.org