Search code examples
arraysswiftenumerate

Array after an element is > 0 change all elements to that value until next non zero value


I have an array that is for example

[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0] 

How can I change the element with 0 value if the previous value > 0? so

[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]

becomes

[0.0, 0.0, 55.0, 55.0, 55.0, 55.0, 55.0, 22.0, 22.0, 55.0]

I have tried the following and it removes the zeros and nothing else.

func weightArrayRemovedZero(array: [Double])->[Double]{

 var arrayToAlter = [Double]()

 for(index,item) in array.enumerated() {

   print("The \(item) is at index:\(index)")

   if item == 0.0 {
     if index > 0 && index < array.count - 1 {

       if array[index - 1] != 0.0 {
         let nonZeroElement = array[index - 1]
         arrayToAlter.append(nonZeroElement)
       }
     }


   } else {
     arrayToAlter.append(item)
   }
 }

 return arrayToAlter
}

Solution

  • map seems to be the natural approach to me:

    var last = 0.0
    let mapped = values.map { elem -> (Double) in
        last = elem > 0.0 ? elem : last
        return last
    }
    

    Generally speaking, map is your go to when you want to change one collection into another collection with a one-to-one element mapping.