2

Im new here so correct me if I've formatted this incorrectly (also new to swift) but basically what I'm trying to do is take an array of dates and numbers and if any of the dates are the same combine the numbers into one entry.

so this

//This is how i format the data after i pull it from core data
var dateAndEntry = [(String, Double)]

//i've split them into two seperate arrays for sorting, but I feel like theres a better way i don't know
var dates = ["01/01/2016", "02/01/2016", "02/01/2016", "04/01/2016", "05/01/2016", "06/01/2016","07/01/2016","07/01/2016"]
var entries = [-14,2,8,9,-1,8,25,6]

becomes this

var dates = ["01/01/2016", "02/01/2016", "04/01/2016", "05/01/2016", "06/01/2016","07/01/2016"]
var entries = [-14,10,9,-1,8,19]

I've tried doing this but i can only get it so that it makes a new array that only contains the new values rather than allowing me to get the duplicated values, combine, insert at index then delete original entries in the two arrays.

func combineDuplicates(dates: [String]) -> [String]{
    var output: [String] = []
    var checked = Set<String>()
    for date in dates {

        if !checked.contains(date) {
            checked.insert(date)
            output.append(date)
        }
    }
    print(output)
    return output
}

let sorted = combineDuplicates(dates)
print(sorted)

and yes i have looked on google and here for answers but turned up nothing.

Any solutions, explanations, help, pointers or references to other questions or sources I may have missed would all be greatly appreciated.

1 Answer 1

3

This will get you a dictionary with keys the dates and values the sum of entries for each date:

dates.enumerate().reduce([String:Int]()) { dict, item in
    var dict = dict
    dict[item.1] = (dict[item.1] ?? 0) + entries[item.0]
    return dict
}
// ["06/01/2016": 8, "04/01/2016": 9, "01/01/2016": -14, "05/01/2016": -1, "07/01/2016": 31, "02/01/2016": 10]
Sign up to request clarification or add additional context in comments.

15 Comments

damn, too slow. Add .map { $0 } at the end to turn it back into an array.
@RMenke you can add an answer referring to mine, plus the map call. If would be a shame for people to not see your suggestion which completes my answer.
Don't worry about it. If I cared about the credit or the rep I would have posted it as answer. I only care about forming the best possible answer. In this case it is yours.
@RMenke the syntax it is old. I am just showing Cristik that he can drop var dict = dict declaring dates.enumerate().reduce([String:Int]()) { var dict, item in
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.