I would like to know if there is a neat way of replacing all zeros in an array with the previous nonzero value in Scala. Similar to this question: pandas replace zeros with previous non zero value
I can achieve this for the case where there are no consecutive zeros with sliding:
scala> Array(1,2,3,0,5,6,7).sliding(2).map {case Array(v1, v2) => if (v2==0) v1 else v2}.toArray
res293: Array[Int] = Array(2, 3, 3, 5, 6, 7)
although I then have to append the first value (which I would do before converting to array).
The above code does not work if there are two consecutive zeros:
scala> Array(1,2,3,0,0,6,7).sliding(2).map {case Array(v1, v2) => if (v2==0) v1 else v2}.toArray
res294: Array[Int] = Array(2, 3, 3, 0, 6, 7)
The desired result is Array(2,3,3,3,6,7)
.
This would be easy to do with a for loop; is it possible with a functional approach?