1、取出数组中重复的元素(不重复的不提取,合并重复的元素)
let datas = [1, 2, 3, 3, 2, 1, 1, 1, 2, 3, 4]
let duplicate = Set(datas.filter({ (number) in datas.filter({ $0 == number }).count > 1 }))
// [2, 3, 1]
2、合并重复的元素 (不重复的也提取)
let datas = [1, 2, 3, 3, 2, 1, 1, 1, 2, 3, 4]
Set(datas)
// [2, 4, 3, 1]
3、剔除数组中重复的元素
let datas = [1, 2, 3, 3, 2, 1, 1, 1, 2, 3, 4]
let different = Set(datas).filter({ (number) in datas.filter({ $0 == number }).count == 1 })
// [4]
4、将重复的元素提取出来,生成新的数组
let datas = [1, 2, 3, 3, 2, 1, 1, 1, 2, 3, 4]
let newArray = Set(datas).map({ (number) in datas.filter({ $0 == number }) })
// [[2, 2, 2], [4], [3, 3, 3], [1, 1, 1, 1]]
如果想要保留顺序,那么这么做:
let datas = [3, 1, 2, 3, 3, 2, 1, 1, 1, 2, 3, 4]
var groupped: [[Int]] = []
datas.enumerated().forEach { (index, element) in
if let index = groupped.index(where: { $0.last == element }) {
groupped[index].append(element)
} else {
groupped.append([element])
}
}
// [[3, 3, 3, 3], [1, 1, 1, 1], [2, 2, 2], [4]]
网友评论