如何从数组中删除重复数据
Posted
技术标签:
【中文标题】如何从数组中删除重复数据【英文标题】:How to remove duplicates data from array 【发布时间】:2022-01-19 07:15:30 【问题描述】:我正在我的应用中实现关注和关注功能。从 Firestone 获取数据并传递到函数数组数据后,我将数据存储在 firestore 上。
FirebaseReference(.Users).getDocuments(snapshot, error) in
if error != nil
print("Document Error: ", error!)
else
if let doc = snapshot, doc.isEmpty == false
print("User Document is present.")
let desc = doc.documents
for item in desc
let user = item.data()
let name = user["name"] as! String
let uid = user["userID"] as! String
let img = user["imgUrl"] as? String
FirebaseReference(.Users).document(FUser.currentUser()?.userID ?? "").collection("Following").getDocuments(snapshot1,error) in
if error != nil
print("Document Error: ", error!)
else
if let doc1 = snapshot1, doc1.isEmpty == false
let data = doc1.documents
var followingid = ""
for newitem in data
let value = newitem.data()
followingid = value["followedToUserId"] as? String ?? ""
self.getPostData(name: name, uid: uid, img: img ?? "",followingId: followingid )
else
self.getPostData(name: name, uid: uid, img: img ?? "",followingId:"NA")
else
print("User Document is not present.")
如果我在这个函数中传递数据 self.getPostData() 在 for 循环中,我的数据会成倍增加。请任何人都可以帮助我解决这个问题。
谢谢
【问题讨论】:
是followingId相乘,其他(name,uid,,mage)不是还是所有数据都相乘?最好看看你的阵列给我们一个明确的答案 为什么不确保不添加重复项而不是删除重复项? 如果我在 for 循环之外编写函数,则在第二个中添加重复项,而不是添加重复项 @AnandVishwakarma 你的final data structure
应该是什么?可以添加getPostData
的函数定义吗
那么问题出在getPostData函数上吗?
【参考方案1】:
使用集合
let a = ["hai","hai","hello"]
let unique = Array(Set(a))
print(unique)
output should -> ["hai", "hello"]
NB: result won't be in order, if you want remove a duplicate model , model just needs to confirm the class Hashable and the process and result would be same
struct User: Hashable
var name: String
var age: Int
let a = [User(name: "a",age:15), User(name: "a",age:15),User(name: "b",age:30)]
let unique = Array(Set(a))
print(unique)
result -> [main.User(name: "a", age: 15), main.User(name: "b", age: 30)]
【讨论】:
以上是关于如何从数组中删除重复数据的主要内容,如果未能解决你的问题,请参考以下文章