KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using .multiSort() to Sort Synchronized Collections
PRODUCT: 4D | VERSION: 20 R | PLATFORM: Mac & Win
Published On: August 20, 2024

In 4D v20 R3, a function for sorting synchronized collections .multiSort() was introduced. It allows the developer to pass in multiple collections and preform both multilevel and single level synchronized sorts.

The .multiSort() function does modify the original collection as well as any columns inserted into the colToSort parameter. The sort it performs is a stable sort, meaning that elements that are equal to each other will always be sorted in the order they appeared in the input.

If .multiSort() is called with no parameters, it simply acts the same as .sort() and performs a sort on the one collection.

var $col1; $col2; $col3 : Collection

$col1:=New collection("Ace"; "Jack"; 1; 2; 7; "King"; 3; 6; 4; "Queen")
$col2:=New collection("Hearts"; "Spades"; "Clubs"; "Diamonds"; "Hearts"; "Spades"; "Clubs"; "Diamonds"; "Hearts"; "Spades")
$col3:=New collection(1; 2; 3; 4; 5; 6; 7; 8; 9; 10)

//multisort just acting as a sort; does not affect the other columns as they were not input
$col1.multiSort()



If instead .multiSort() is called with both the other columns inserted, they will sort all columns based on the sorting of $col1. Example: if the value at index 3 of $col1 will be first after sorting, both $col1 and $col2 at index 3 will be sorted to be first as well.

//reset $col1 from first example
$col1:=["Ace"; "Jack"; 1; 2; 7; "King"; 3; 6; 4; "Queen"]

$col1.multiSort([$col2; $col3])



If I want to sort back to the order of $col3, this can be called.

$col3.multiSort([$col1; $col2])

The following shows how this function uses a stable sort as it keeps in input order of repeated elements in $col2.

$col2.multiSort([$col1; $col3])



If any of the collections are of a different size, the error "The size of the collections doesn't match." will occur to let the developer know that the columns cannot be synchronized.