Pangu
Pangu

Reputation: 3819

iOS Swift: Track and store indices of all duplicate values in an array?

I recently asked this question: iOS Swift: How to store the index of all duplicate values in array?

I was provided with the exact answer to my question, but I found that I could not use it to implement what I need in my code.

I'm trying to store all the indices of any duplicate values of a Date array and store in another array [ [Int] ].

For example, here's my Date array:

let dates = [2016-01-02 08:00:00 +0000, 2016-01-02 08:00:00 +0000,
             2016-02-02 08:00:00 +0000, 2016-03-02 08:00:00 +0000, 
             2016-05-01 08:00:00 +0000, 2016-05-01 08:00:00 +0000]

What I am trying to do, similar to my previous question is to store all the indices of all repeated Date values into a separate array.

For example, the following array would contain:

repeatedIndices = [ [0, 1], [2], [3], [4, 5] ]

where indices 0 and 1 contains the repeated date 2016-01-02 08:00:00 +0000 and indices 4 and 5 contains the repeated date 2016-05-01 08:00:00 +0000.

My previous question had an answer that provided it in a [ String: [Int] ], and being a beginner, I don't know how to manipulate it to work with my code since the dictionary is unordered and I need an ordered array.

Please mark as duplicate if necessary, but I didn't want to edit the question and un-mark the answer as it would be unfair.

Thank you.

Upvotes: 0

Views: 282

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

Using an [Date:[Int]] dictionary with your example values,

var duplicatedDict : [Date:[Int]] = [:]

for (index,date) in datesArray.enumerated() {
            if(duplicatedDict[date] == nil)
            {
                duplicatedDict[date] = [index]
            }else
            {
                duplicatedDict[date]?.append(index)
            }
        }

debugPrint(duplicatedDict)

So far, so good we have this as result in Console

[2016-02-02 08:00:00 +0000: [2], 2016-05-01 08:00:00 +0000: [5, 6], 2016-03-02 08:00:00 +0000: [3, 4], 2016-01-02 08:00:00 +0000: [0, 1]]

Then we need to cycle over the sorted dictionary keys and add to array the values in each key array

func returnValuesOrdered() ->[[Int]]{

        var result : [[Int]] = []

        for key in duplicatedDict.keys.sorted(by: {$0 < $1})
        {
            result.append(duplicatedDict[key]!)
        }

        debugPrint(result)
        return result
    }

result in Console

[[0, 1], [2], [3, 4], [5, 6]]

Hope this helps you

Upvotes: 1

Related Questions