KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Sort Array based off length of element
PRODUCT: 4D | VERSION: 14.3 | PLATFORM: Mac & Win
Published On: January 30, 2015

Below is a method that will sort the array based off the length of the elements in the array.

// Method: Sort_Array_By_Length
// Parameters
// $1 - Pointer to array to be sorted
// $2 - (1) to sort by increasing order, (-1) to sort by decreasing order
// ----------------------------------------------------

C_POINTER($arr;$1)
C_LONGINT($i;$order;$2)
$arr:=$1
If (Count parameters>1)
  $order:=$2
  If ($order#1) & ($order#-1)
    $order:=1
  End if
Else
  $order:=1
End if

$arrSize:=Size of array($arr->)
ARRAY LONGINT($arrL;0)

For ($i;1;$arrSize)
  APPEND TO ARRAY($arrL;Length(String($arr->{$i})))
End for
ARRAY POINTER($ptrArr;2)
ARRAY LONGINT($srtArr;2)
$ptrArr{1}:=$arr
$srtArr{1}:=0
$ptrArr{2}:=->$arrL
$srtArr{2}:=$order
MULTI SORT ARRAY($ptrArr;$srtArr)


Below are a couple of examples of sorting an array. Assume the following array"
ARRAY TEXT($arr;0)
APPEND TO ARRAY($arr;"1234")
APPEND TO ARRAY($arr;"12345")
APPEND TO ARRAY($arr;"1")
APPEND TO ARRAY($arr;"123")
APPEND TO ARRAY($arr;"12")
APPEND TO ARRAY($arr;"2")
APPEND TO ARRAY($arr;"21")


The following code sorts the array by the length of the elements in increasing order:
UTIL_SORT_ARRAY_BY_LENGTH(->$arr;1)

The code above will yield the following results:


The following code sorts the array by the length of the elements in decreasing order:
UTIL_SORT_ARRAY_BY_LENGTH(->$arr;-1)

The code above will yield the following results: