4D v18

collection.reduce( )

Home

 
4D v18
collection.reduce( )

collection.reduce( )  


 

The collection.reduce( ) method applies the methodName callback method against an accumulator and each element in the collection (from left to right) to reduce it to a single value.

Note: This method does not modify the original collection.

In methodName, pass the name of the method to use to evaluate collection elements, along with its parameter(s) in param (optional). methodName takes each collection element and performs any desired operation to accumulate the result into $1.accumulator, which is returned in $1.value.

You can pass the value to initialize the accumulator in initValue. If omitted, $1.accumulator starts with Undefined.

methodName receives the following parameters:

  • in $1.value: element value to be processed 
  • in $2: param
  • in $N...: param2...paramN

methodName sets the following parameter(s):

  • $1.accumulator: value to be modified by the function and which is initialized by initValue.
  • $1.stop (boolean, optional): true to stop the method callback. The returned value is the last calculated.

 C_COLLECTION($c)
 $c:=New collection(5;3;5;1;3;4;4;6;2;2)
 $r:=$c.reduce("Multiply";1) //returns 86400

With the following Multiply method:

 If(Value type($1.value)=Is real)
    $1.accumulator:=$1.accumulator*$1.value
 End if

This example allows reducing several collection elements to a single one:

 C_COLLECTION($c;$r)
 $c:=New collection
 $c.push(New collection(0;1))
 $c.push(New collection(2;3))
 $c.push(New collection(4;5))
 $c.push(New collection(6;7))
 $r:=$c.reduce("Flatten") //$r=[0,1,2,3,4,5,6,7]

With the following Flatten method:

 If($1.accumulator=Null)
    $1.accumulator:=New collection
 End if
 $1.accumulator.combine($1.value)

 
PROPERTIES 

Product: 4D
Theme: Collections

This command can be run in preemptive processes

 
PAGE CONTENTS 
 
HISTORY 

 
ARTICLE USAGE

4D Language Reference ( 4D v18)