updatearray with foreach

How do i retain updated array's positional values during each iteration of foreach ?

Example :

Trying to update second and third index to 1 depending on the rule input

ri!selectedMonths -> {2,3}

desired result -> {0,1,1,0,0,0,0,0,0,0,0,0}

 

load(

local!allmonths:index({},enumerate(12),0),
 

a!forEach(
  items: ri!selectedMonths,
  expression:
  fn!updatearray(local!allmonths,fv!item,1)

)
)

 

The result of the rule repeats itself for every execution without retaining the value from previous execution.

Second execution updates second index position , third execution updates third position but reevaluates the array without retaining value from second execution.

  Discussion posts and replies are publicly visible

  • Hi Ravi, try incorporating reduce() function in your logic to retain the results of each iteration and pass the result as a base value for next iteration.
  • Hi, I didn't understand why u r using a!forEach() function. If you req to update specific index in an array, u can simply use the updatearray() as below

    load(
    local!months:index({},enumerate(12),0),
    local!array:fn!updatearray(local!months,ri!selectedMonths,1),
    local!array
    )
    If this is not what you required, then plz explain in more detail what u r trying to achieve.
  • Hi Ravi,

    fn!updatearray does not actually mutate the array that is passed to it. Insted, it returns what the value of the array would be after the update. In general, local variables can only be modified inside of saveInto's.

    There are a few options for returning the desired results, though! As mentioned above, you could use fn!reduce (which is like apply, but it passes the result of each iteration onto the next iteration) to loop over the array, or you could simply pass all the indices you wish to update into updatearray (it supports updating several indices at once).

    If you wish to achieve the result using a a!forEach, though, you could do something like the below code, which will iterate over each element of the array and return an updated element if appropriate. I hope this helps!

    load(
      local!allMonths: repeat(12, 0),
      a!forEach(
        items: local!allMonths,
        expression: if(
          contains(
            ri!selectedMonths,
            fv!index
          ),
          1,
          fv!item
        )
      )
    )