0

I have two arrays, which contain objects. Each object has a property "id". If id has the same value - it is duplicates. How can i find and delete duplicates by matching properties ?

Now i use this but sometimes it misses out and writes duplicates into DB

 func checkForDupl() {

        for var i = 0; i < JSONStorage.count; i++ {

            for var b = 0; b < CDStorage.count; b++ {

                if JSONStorage[i]!.id == CDStorage[b]!.id {

                    JSONStorage.removeAtIndex(i)
                    if JSONStorage.isEmpty {
                        return
                    }
                }
            }
        }
    }
Alexey K
  • 6,537
  • 18
  • 60
  • 118
  • 1
    You are removing an item from the array, but you are still incrementing __i__, so for each duplicate found, there is the possibility of missing one. – David Skrundz Jul 29 '15 at 15:53

1 Answers1

0

I modified your function so it no longer misses duplicates

func checkForDupl() {
    var i = 0
    OUTER_LOOP: while i < JSONStorage.count {
        for j in 0..<CDStorage.count {
            if JSONStorage[i]!.id == CDStorage[j]!.id {
                JSONStorage.removeAtIndex(i)
                continue OUTER_LOOP
            }
        }
        ++i
    }
}

NOTE: This function only removes items from JSONStorage that are present in CDStorage. It does not removeduplicates within JSONStorage

David Skrundz
  • 13,067
  • 6
  • 42
  • 66
  • Great Thanks! I have never seen OUTER_LOOP construction before, what to google about ? Thanks again! – Alexey K Jul 29 '15 at 16:48
  • Its a label. When using `continue` or `break`, it just exist from the innermost loop. using `continue – David Skrundz Jul 29 '15 at 16:50