Tech Tip: Comparing two arrays of any types
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: May 10, 2017
The method below is a way of comparing two arrays using the Json command JSON Stringify array and SHA1 message-digest algorithm through Generate digest. This method will return a boolean as a result.
Json is used in the method to compare two arrays when both are text array or object array. Because Json is not case sensitive . The SHA1 will be used for the rest The array Type.
------------------------------------------------------------------------------------ // Method name : comparearray // Method description : Method will compare two arrays and return True if they are identical if not return False // input : // $1 (POINTER ) - Pointer on Array // $2 (POINTER ) - Pointer on Array // output : // $0 - return a boolean ------------------------------------------------------------------------------------ C_BOOLEAN($0) C_POINTER($1;$2) $0:=False $arr1_p:=$1 $arr2_p:=$2 If (Size of array($1->)=Size of array($2->)) SORT ARRAY($1->;>) SORT ARRAY($2->;>) If(((Type($1->)=Text array)&(Type($2->)=Text array))|((Type($1->)=Object array) & (Type($2->)=Object array))) $0:=(JSON Stringify array($1->)=JSON Stringify array($2->)) Else C_BLOB($blb1_x;$blb2_x) VARIABLE TO BLOB($1->;$blb1_x) VARIABLE TO BLOB($2->;$blb2_x) $digest1_t:=Generate digest($blb1_x;SHA1 digest) $digest2_t:=Generate digest($blb2_x;SHA1 digest) $0:=($digest1_t=$digest2_t) End if End if |
Exemple of usage :
ARRAY TEXT (tb1;1) ARRAY TEXT (tb2;1) tb1{1}:="Test" tb2{1}:="Test2" comparearray (->tb1;->tb2) |
Commented by Alberto Bachler Klein on May 24, 2017 at 7:49 AM
Be aware of this limitations:
- if the two arrays have same element values in different positions they are still considered identical
- the arrays are returned sorted after the call to this method
- comparison is not case sensitive for text and object arrays
- arrays of different types with 0 elements are considered identical
- pointer arrays are not supported (i thinkā¦)