我是新来的,所以如果我的格式不正确,请纠正我(对于 swift 来说也是新的),但基本上我想做的是获取日期和数字的数组,如果任何日期相同,则将将数字合并到一个条目中。
所以这个
//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]
变成这样
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]
我已经尝试这样做,但我只能得到它,以便它创建一个仅包含新值的新数组,而不是允许我获取重复的值,组合,在索引处插入,然后删除两个中的原始条目数组。
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)
是的,我在谷歌和这里寻找答案,但一无所获。
任何解决方案、解释、帮助、指示或对我可能错过的其他问题或来源的引用都将不胜感激。
最佳答案
这将为您提供一个字典,其中键为日期,值为每个日期的条目总和:
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]
关于ios - 查找并组合数组中的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622665/