Skip to main content
July 7, 2021
Solved

Repeat values in an array

  • July 7, 2021
  • 2 replies
  • 0 views

I have an array where I would like to replace the zero values with the previous non-zero value.

i.e. convert { 15, 0, 0, 23, 0, 0, 0 } to { 15, 15, 15, 23, 23, 23, 23 }

Any ideas?

    Best answer by mikes0011

    Pretty much the exact same thing was answered several months ago, here.  The only real difference in that case is the zero values are replaced by the next nonzero member instead of the previous, but that should require only a very simple adjustment of the code.

    2 replies

    mikes0011
    mikes0011Answer
    Brainy
    July 7, 2021

    Pretty much the exact same thing was answered several months ago, here.  The only real difference in that case is the zero values are replaced by the next nonzero member instead of the previous, but that should require only a very simple adjustment of the code.

    The Expression Guru
    csteward
    July 7, 2021

    Additionally, here's some sample code that should fit the bill:

    a!localVariables(
      local!data: {15,0,0,23,0,0,0},
      local!nonZeroIndexes: a!forEach(
        items: local!data,
        expression: if(fv!item=0,null,fv!index)
      ),
      
      a!forEach(
        items: local!data,
        expression: if(
          fv!item<>0,
          fv!item,
          index(
            local!data,
            max(rdrop(local!nonZeroIndexes,count(local!nonZeroIndexes)-fv!index)),
            null
          )
        )
      )
    )