This is the legacy 4D documentation web site. Documentations are progressively being moved to developer.4d.com

Home

 
4D v19.8
collection.reduce( )

collection.reduce( ) 


 

collection.reduce ( methodName {; initValue}{; param}{; param2 ; ... ; paramN} ) -> Function result 
Parameter Type   Description
methodName  Text in Name of the function to call to process collection elements
initValue  Text, Number, Object, Collection, Date, Boolean in Value to use as the first argument to the first call of methodName
param  Expression in Parameter(s) to pass to methodName
Function result  Text, Number, Object, Collection, Date, Boolean in Result of the accumulator value

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
Number: 705248

This command can be run in preemptive processes

 
PAGE CONTENTS 
 
HISTORY 

Created: 4D v16 R6

 
ARTICLE USAGE

4D Language Reference ( 4D v19)
4D Language Reference ( 4D v19.1)
4D Language Reference ( 4D v19.4)
4D Language Reference ( 4D v19.5)
4D Language Reference ( 4D v19.6)
4D Language Reference ( 4D v19.7)
4D Language Reference ( 4D v19.8)