Skip to main content
June 1, 2022
Solved

Update variable inside foreach loop

  • June 1, 2022
  • 5 replies
  • 0 views

Hi Community

I have a case that I need to decrement counter in foreach loop

is it poosible ?

My code:

local!numbers: {2, 12, 14, 22, 32},

local!counter: 100,

local!loop: a!foreach(

     local!numbers,

     /* need here to decrement the counter */

)

Best answer by stefanhelzle0001

OK. Check out this example.

Each iteration subtracts the sum of the first few items in the list. enumerate() creates a list of number from 0 to n-1. Adding 1 turns it into 1 to n. index() then picks the values at these indexes.

a!localVariables(
  local!numbers: {2, 12, 14, 22, 32},
  
  local!counter: 100,
  
  a!forEach(
    items: local!numbers,
    expression: local!counter - sum(index(local!numbers, (1 + enumerate(fv!index)), 0))
  )
)

5 replies

agamb0001
June 1, 2022

You can try something as

local!counter - fv!index

stefanhelzle0001
Brainy
June 1, 2022

As Appian expressions is a functional language, modifying the value of a variable is not supported. But, in my experience, this kind of problem can easily solved in a different way. So, what do you want to achieve?

June 1, 2022

I need to save in each iteration the counter - each number in the loop, then map them to list.

For example:

[

     98,     /* 100 - 2 */

     86,     /* 98 - 12 */

     72,     /* 86 - 14 */

]

stefanhelzle0001
Brainy
June 1, 2022

OK. Check out this example.

Each iteration subtracts the sum of the first few items in the list. enumerate() creates a list of number from 0 to n-1. Adding 1 turns it into 1 to n. index() then picks the values at these indexes.

a!localVariables(
  local!numbers: {2, 12, 14, 22, 32},
  
  local!counter: 100,
  
  a!forEach(
    items: local!numbers,
    expression: local!counter - sum(index(local!numbers, (1 + enumerate(fv!index)), 0))
  )
)