Home > Back-end >  Swift: Remove object from array if timestamp is within certain range of previous timestamp?
Swift: Remove object from array if timestamp is within certain range of previous timestamp?

Time:07-07

I have an array of objects that contain a timestamp. I want to drop all the objects that are in 6 hours chunks. Eg, reducing the following [Obj(00:00), Obj(04:00), Obj(06:01), Obj(07:00), Obj(12:00)] to [Obj(00:00), Obj(06:01), Obj(12:00)].

How would I go about this?

The object is a CoreData object that ends up as follows:

struct Entry {

var intensity: Float?
var timestamp: Date?

}

CodePudding user response:

With a simple for loop:

var withForLoop: [Entry] = []
for anEntry in initialArray {
    // If it's empty, we add it if there is really a timestamp
    guard let lastEntry = withForLoop.last, let lastEntryDate = lastEntry.timestamp else { withForLoop.append(anEntry); continue }

    // If there is no timestamp, we skip it
    guard let currentEntryDate = anEntry.timestamp else { continue }
    // Here I took hours in "absolute", meaning, I don't consider a change of hour (saving time)
    // Create your own comparison if needed
    if currentEntryDate.timeIntervalSince(lastEntryDate) > 3600 * 6 {
        withForLoop.append(anEntry)
    } // Else, there was less than 6 hours difference, we don't append it
}
print(withForLoop)

With a reduce(into:_):

let output = initialArray.reduce(into: [Entry]()) { partialResult, current in
    // If it's empty, we add it if there is really a timestamp
    guard let lastEntry = partialResult.last, let lastEntryDate = lastEntry.timestamp else { partialResult.append(current); return }

    // If there is no timestamp, we skip it
    guard let currentEntryDate = current.timestamp else { return }
    // Here I took hours in "absolute", meaning, I don't consider a change of hour (saving time)
    // Create your own comparison if needed
    if currentEntryDate.timeIntervalSince(lastEntryDate) > 3600 * 6 {
        partialResult.append(current)
    } // Else, there was less than 6 hours difference, we don't append it
}
print(output)

Warning:

  • I assume the entries to be sorted.
  • I used 3600 * 6 for the calculation, but it might no be "correct". It depends on what you want to do. It doesn't manage the "hour saving" for instance.
  • Related