Remove Objects with Duplicate Properties from Swift Array

Remove objects with duplicate properties from Swift array

I am going to suggest 2 solutions.

Both approaches will need Post to be Hashable and Equatable

Conforming Post to Hashable and Equatable

Here I am assuming your Post struct (or class) has an id property of type String.

struct Post: Hashable, Equatable {
let id: String
var hashValue: Int { get { return id.hashValue } }
}

func ==(left:Post, right:Post) -> Bool {
return left.id == right.id
}

Solution 1 (losing the original order)

To remove duplicated you can use a Set

let uniquePosts = Array(Set(posts))

Solution 2 (preserving the order)

var alreadyThere = Set()
let uniquePosts = posts.flatMap { (post) -> Post? in
guard !alreadyThere.contains(post) else { return nil }
alreadyThere.insert(post)
return post
}

Removing Duplicates From Array of Custom Objects Swift

You can do it with a set of strings, like this:

var seen = Set()
var unique = [DisplayMessage]
for message in messagesWithDuplicates {
if !seen.contains(message.id!) {
unique.append(message)
seen.insert(message.id!)
}
}

The idea is to keep a set of all IDs that we've seen so far, go through all items in a loop, and add ones the IDs of which we have not seen.

Swift removing duplicate from array of object

I think it is easier way to solve this problem.
First your datastruct class should be extend NSObject.
Then Add isEqual(_ object: Any?) method in your datastruct. like this way.

class datastruct : NSObject {

var id: Int?
var name: String?

init(add: NSDictionary) {
id = add["id"] as? Int
name = add["name"] as? String
}

override func isEqual(_ object: Any?) -> Bool {
let obj = object as! datastruct
if self.id == obj.id {
return true
} else {
return false
}
}
}

Now you can check for duplication.

if let res = list[i] as? NSDictionary {
let dataStructObj = datastruct(add: res)
if !data.contains(dataStructObj) {
self.data.append(dataStructObj)
}

}

I hope it will help you.

Removing duplicate elements from an array in Swift

You can roll your own, e.g. like this:

func unique(source: S) -> [T] where S.Iterator.Element == T {
var buffer = [T]()
var added = Set()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}

let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60]

And as an extension for Array:

extension Array where Element: Hashable {
func uniqued() -> Array {
var buffer = Array()
var added = Set()
for elem in self {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
}

Or more elegantly (Swift 4/5):

extension Sequence where Element: Hashable {
func uniqued() -> [Element] {
var set = Set()
return filter { set.insert($0).inserted }
}
}

Which would be used:

[1,2,4,2,1].uniqued()  // => [1,2,4]

Remove objects with duplicate date property from Array

Use date components to unique on, so you ignore the time part

struct Record {
let date: Date
let name: String
}

let now = Date()
let soon = Date(timeIntervalSinceNow: 100)
let future = Calendar.current.date(byAdding: .day, value: 1, to: now)!
let records = [Record(date: now, name: "Now"),
Record(date: soon, name: "Soon"), // same day so should be removed
Record(date: future, name: "Future")]


var unique = Set()
let result = records.filter {
let comps = Calendar.current.dateComponents([.day, .month, .year], from: $0.date)
if unique.contains(comps) {
return false
}
unique.insert(comps)
return true
}
print(result)

// [Record(date: 2018-10-11 13:47:17 +0000, name: "Now"),
// Record(date: 2018-10-12 13:47:17 +0000, name: "Future")]

How to remove duplicate elements from an array in Swift 5?

Most efficient way if you don’t care about maintaining the original order in the array

let uniqueUsers = Array(Set(users))

How to remove duplicate elements inside an array - swift 3

Make sure that InputSource implements Hashable, otherwise Swift can't know which elements are equal and which are not.

You just do this:

let withoutDuplicates = Array(Set(images))

Explanation:

images is turned into a set first. This removes all the duplicates because sets can only contain distinct elements. Then we convert the set back to an array.

According to this answer, this is probably optimized by the compiler.

The disadvantage of this is that it might not preserve the order of the original array.

Remove duplicate elements from object array

You need to make Transaction object Hashable. Try this

struct Transaction{
var transId: String
}
extension Transaction: Hashable{
static func ==(lhs: Transaction, rhs: Transaction) -> Bool {
return lhs.transId == rhs.transId
}
}


var budgetData = [Transaction(transId: "a"), Transaction(transId:"c"),
Transaction(transId: "a"), Transaction(transId: "d")]
var tranSet = Set()
budgetData = budgetData.filter { (transaction) -> Bool in

if !tranSet.contains(transaction){
tranSet.insert(transaction)
return true
}
return false
}


Related Topics



Leave a reply



Submit