Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.



Excerpt
hiddentrue

forEach($var, set, script) Iterates over an Array or Recordset and processes a script for each entry.


Function: forEach()

Iterates over an Array or Recordset and processes a script for each entry.

...

forEach() is like every other function in that it returns a value. In this case the value returned is an Array of the results of running script for each entry in set. Note that the result of running the script is the value of the last script item to be processed before the the next iteration.

Examples


In the first two examples, let $numberList = [1,2,3,4,5,6,7,8,9,10], 

Code Block
forEach($number, $numberList, 

   $currentValue = $number

),

Returns 10, as forEach() returns the value of the final expression to be evaluated in its final iteration.


Code Block
forEach($number, $numberList,  

   $sumOfNumbers = $sumOfNumbers + $number

)

Returns 55.


Detailed example: (step-by-step)

Code Block
forEach( $customerType, customers.type, 

   $total = $total + 1, 

   if( $customerType == "Business", continue() ), 

   $nonBusiness = $nonBusiness + 1, 

   subString($customerType, 1, 6) 
)


All entries after the second parameter of the above forEach() comprise the script that will be processed for each entry in customers.type. Processing is as follows:

...

The forEach() function above therefore returns an Array of the first 6 characters of each non business customer type in the supplied list. The values of $total (a count of all customer types), $nonBusiness (a count of all non-business customer types) and $customerType (the last customer type processed) will be available to subsequent Attribute Expressions for the current Stream Item calculation.


Commonly, you will might not want to return a list from forEach(), but calculate some values in the loop to use later. For example, if you had an attribute TotalCustNumber, you might create an attribute expression:

Code Block
do( 
   forEach( $customerType, customers.type, 

      $total = $total + 1, 
      if( $customerType == "Business", continue() ), 
      $nonBusiness = $nonBusiness + 1 
   ), 

   $total 
)


This would calculate the total number of customers (in $total) and write this value to the attribute.

...