4D v19

collection.sort( )

Home

 
4D v19
collection.sort( )

collection.sort( )  


 

The collection.sort( ) method sorts the elements of the original collection and also returns the sorted collection.

Note: This method modifies the original collection.

If collection.sort( ) is called with no parameters, only scalar values (number, text, date, booleans) are sorted. Elements are sorted by default in ascending order, according to their type.

If you want to sort the collection elements in some other order or sort any type of element, you must supply in methodName a comparison method that compares two values and returns true in $1.result if the first value is lower than the second value. You can provide additional parameters to methodName if necessary.

  • methodName will receive the following parameters:
    • $1 (object), where:
      • $1.value (any type): first element value to be compared
      • $1.value2 (any type): second element value to be compared
    • $2...$N (any type): extra parameters
  • methodName sets the following parameter:
    • $1.result (boolean): true if $1.value < $1.value2, false otherwise

If the collection contains elements of different types, they are first grouped by type and sorted afterwards. Types are returned in the following order:

  1. null
  2. booleans
  3. strings
  4. numbers
  5. objects
  6. collections
  7. dates

 C_COLLECTION($col)
 $col:=New collection("Tom";5;"Mary";3;"Henry";1;"Jane";4;"Artie";6;"Chip";2)
 $col2:=$col.sort() // $col2=["Artie","Chip","Henry","Jane","Mary","Tom",1,2,3,4,5,6]
  // $col=["Artie","Chip","Henry","Jane","Mary","Tom",1,2,3,4,5,6]

 C_COLLECTION($col)
 $col:=New collection(10;20)
 $col2:=$col.push(5;3;1;4;6;2).sort() //$col2=[1,2,3,4,5,6,10,20]

 C_COLLECTION($col)
 $col:=New collection(33;4;66;1111;222)
 $col2:=$col.sort() //numerical sort: [4,33,66,222,1111]
 $col3:=$col.sort("numberOrder") //alphabetical sort: [1111,222,33,4,66]

  //numberOrder project method
 C_OBJECT($1)
 $1.result:=String($1.value)<String($1.value2)



See also 

collection.orderBy( )
collection.orderByMethod( )

 
PROPERTIES 

Product: 4D
Theme: Collections

This command can be run in preemptive processes

 
PAGE CONTENTS 
 
HISTORY 

 
ARTICLE USAGE

4D Language Reference ( 4D v19)
4D Language Reference ( 4D v19.1)