我想过滤一个对象数组。
struct Person {
let name: String
}
let p1 = Person(name:"test1")
let p2 = Person(name:"test1")
let p3 = Person(name:"test2")
let persons = [p1, p2, p3]
如何过滤persons
列表并返回具有相同名称的人员?
我曾尝试使用过滤方法,但我无法将其应用于多个参数。
我正在寻找像filter
或reduce
这样的功能解决方案,而不是在列表上循环。
答案 0 :(得分:1)
因为您在寻找groupBy
功能,所以我的解决方案
let personsByName = persons.reduce([String:[Person]]()) { (res, person) -> [String:[Person]] in
var res = res
res[person.name] = (res[person.name] ?? []) + [person]
return res
}
现在personsByName
是一个字典,其中键是人的名字,值是具有该名称的所有Person结构
[“test2”:[Person(name:“test2”)],“test1”:[Person(name:“test1”),Person(name:“test1”)]]
let personsLists = Array(
persons.reduce([String:[Person]]()) { (res, person) -> [String:[Person]] in
var res = res
res[person.name] = (res[person.name] ?? []) + [person]
return res
}
.values)
[[Person(name:“test2”)],[Person(name:“test1”),Person(name:“test1”)]]]
答案 1 :(得分:0)
未指定某些细节,因此这可能不是您想要的......
func retrieveDuplicates(persons: [Person]) -> [[Person]] {
let duplicates = persons.reduce([:] as [String: [Person]], combine: {
var dict = $0
dict[$1.name] = (dict[$1.name] ?? []) + [$1]
return dict
}).map{$1}.filter{$0.count > 1}
return duplicates
}
let duplicates = retrieveDuplicates(persons)
print(duplicates) //->[[Person(name: "test1"), Person(name: "test1")]]
let p4 = Person(name:"test3")
let p5 = Person(name:"test3")
let p6 = Person(name:"test3")
let p7 = Person(name:"test1")
let morePersons = [p1, p2, p3, p4, p5, p6, p7]
let moreDuplicates = retrieveDuplicates(morePersons)
print(moreDuplicates) //->[[Person(name: "test3"), Person(name: "test3"), Person(name: "test3")], [Person(name: "test1"), Person(name: "test1"), Person(name: "test1")]]