Tech Tip: Utility method to find difference of two collections
PRODUCT: 4D | VERSION: 18 | PLATFORM: Mac & Win
Published On: September 22, 2020
Below is a convenient method for finding the difference between two collections. The method takes in two arguments, collection A and collection B, and returns a collection of the elements that are in collection B but are not in collection A, i.e. B - A.
// ---------------------------------------------------- // Method: getCollectionDifference // Description: Compares the elements of collection B against collection A and returns collection (B - A). // Parameters: $1 - Collection A // $2 - Collection B // NOTE: Text comparison is NOT case-sensitive. // ---------------------------------------------------- C_COLLECTION($0;$1;$2;$col_target;$col_source;$col_diff) C_VARIANT($value) If (Count parameters>=2) $col_target:=$1 $col_source:=$2 $col_diff:=New collection For each ($value;$col_source) If ($col_target.indexOf($value)=-1) $col_diff.push($value) End if End for each $0:=$col_diff End if |
The method basically tries to find each element of collection B in collection A, and pushes it into a new collection if not found. Note that, for this method, text comparison is NOT case-sensitive. For example, element "hello" in collection B would be matched to element "HELLO" in collection A, thus would not be included in the returned collection.