KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility Method to Reduce Collections
PRODUCT: 4D | VERSION: 19 R6 | PLATFORM: Mac & Win
Published On: December 12, 2022

Utility method reduceCollection($1) accepts a collection as a parameter and returns a reduced collection.

// reduceCollection($1)

#DECLARE($coll : Collection)->$result : Collection
If (Count parameters=1)
  $result:=$coll.reduce(Formula(Flatten))
End If


// Flatten method
#DECLARE($formula_o : Object)
If ($formula_o.accumulator=Null)
  $formula_o.accumulator:=New collection
End if
$formula_o.accumulator.combine($formula_o.value)

// Example
var $coll1; $coll2; $coll3; $newColl1; $newColl2; $newColl3: Collection
$coll1:=New collection
$coll1.push(New collection(0;1))
$coll1.push(New collection(2;3))
$coll1.push(New collection(4;5))

$coll2:=New collection
$coll2.push(New collection("text1"; "text2"))
$coll2.push(New collection("text3"; "text4"))

$coll3:=New collection
$coll3.push(New collection("name1"; New collection("name2"; "text")))
$coll3.push(New collection("name3"; New collection("name4"; "text")))

// [0,1,2,3,4,5]
$newColl1:=reduceCollection($coll1)

// ["text1", "text2", "text3", "text4"]
$newColl2:=reduceCollection($coll2)

// ["name1",["name2","text"],"name3",["name4","text"]]
$newColl3:=reduceCollection($coll3)


Notice with $newColl1 and $newColl2 the Collections being passed to the utility method contain several collection elements and those collection elements are returned in a single Collection.

The Collection $coll3 is reduced and the result is stored in $newColl3