KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: When to use the .orderBy() and .sort() functions
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: August 12, 2024

In 4D, there are functions for sorting collections including both the .sort(), and .orderBy() functions.

The .orderBy() function sorts a collection in ascending order by default, but allows the developer to specify whether ascending or decending. It does not modify the original collection but instead returns a shallow copy of the original collection.

var $collection; $new_col; $new_col2; $new_col3 : Collection
$collection:=New collection("Ruben"; "Alice"; "Abbey"; "John"; "Bob"; "Leah")
$collection2:=New collection(["B"; "D"; "C"; "A"]; [1; 2; "four"; 3]; "Harry"; ["apple"; 1]; [1; 2; 3; 4; 5; 6]; "Anne")

//orderBy on the original collection.
$new_col:=$collection.orderBy()



For the second collection that includes collections inside, .orderBy() will not sort each individually. It will sort by type, this case being collections and strings, and then sort each type.

$new_col2:=$collection2.orderBy(ck descending)
$new_col3:=$collection2.orderBy(ck ascending)



The .sort() function, on the otherhand, does alter the original collection when called so it may be used if the developer wants to alter the original collection when sorting.

$collection2.sort()