您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Swift在数组中查找重复元素

使用Swift在数组中查找重复元素

要查找重复项,可以按电话号码建立交叉引用,然后将其过滤为仅重复项。例如,考虑:

let contacts = [
    Contact(name: "Rob",     phone: "555-1111"),
    Contact(name: "Richard", phone: "555-2222"),
    Contact(name: "Rachel",  phone: "555-1111"),
    Contact(name: "Loren",   phone: "555-2222"),
    Contact(name: "Mary",    phone: "555-3333"),
    Contact(name: "Susie",   phone: "555-2222")
]

在Swift 4中,您可以使用以下命令构建交叉引用字典:

let crossReference = Dictionary(grouping: contacts, by: { $0.phone })

要么

let crossReference = contacts.reduce(into: [String: [Contact]]()) {
    $0[$1.phone, default: []].append($1)
}

然后,找到重复项:

let duplicates = crossReference
    .filter { $1.count > 1 }                 // filter down to only those with multiple contacts
    .sorted { $0.1.count > $1.1.count }      // if you want, sort in descending order by number of duplicates

显然,请使用对您有意义的任何模型类型,但是上面的模型使用以下Contact类型:

struct Contact {
    let name: String
    let phone: String
}

有很多方法可以实现此目的,因此我将不再关注上述实现细节,而是关注以下概念:通过某个键(例如电话号码)构建交叉引用原始数组,然后将结果过滤为那些具有重复值的键。

听起来您想将反映重复项的结构扁平化为单个联系人数组(我不确定为什么要这么做,因为您丢失了标识彼此重复的结构),但是如果您想这样做,可以flatMap

let flattenedDuplicates = crossReference
    .filter { $1.count > 1 }                 // filter down to only those with multiple contacts
    .flatMap { $0.1 }                        // flatten it down to just array of contacts that are duplicates of something else
Swift 2022/1/1 18:21:55 有392人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶