Aashish Nagar
Aashish Nagar

Reputation: 1227

Find if two strings are same in an array?

I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?

Upvotes: 0

Views: 263

Answers (5)

Alain T.
Alain T.

Reputation: 42143

If you want the list of objects which have the same title as another object in the array, you can do this (assuming title is a String):

var titles     = Set<String>()
let duplicates = array.filter{ !titles.insert($0.title).inserted }

// note: this only lists the second and subsequent element with a given title

if you need their indexes, you can do this:

var titles     = Set<String>()
let dupIndexes = array.enumerated()
                      .filter{ !titles.insert($1.title).inserted }
                      .map{$0.0}

If you want all objects where the title is duplicated (including the first one) you can refine the first approach like this:

var titles     = Set<String>()
let dupTitles  = Set(array.map{$0.title}.filter{!titles.insert($0).inserted})
let dupObjects = array.filter{dupTitles.contains($0.title)}

[EDIT] Swift 4 has a new Dictionary initializer that can be used for this:

let dupObjects = Dictionary(grouping:array){$0.title}
                .filter{$0.value.count > 1}
                .flatMap{$0.value}

In all cases, if the .count of duplicates, dupIndexes or dupObjects is > 0 hen you have at least one duplication in the array

Upvotes: 2

user3441734
user3441734

Reputation: 17544

let s = Set(arr.map{$0.title})
print("found duplicate title?", arr.count != s.count)

in case your title doesn't conform to Hashable protocol, simply use

let s1 = Set(arr1.map{"\($0.title)"})
print("found duplicate title?", arr1.count != s1.count)

Upvotes: 0

Hady Nourallah
Hady Nourallah

Reputation: 442

I would add it to a set of strings from your title then compare the count of both, if count is equal then there are no duplicates, if set count less that mean there are two titles that equal

Upvotes: 0

Vollan
Vollan

Reputation: 1915

var duplicateArray: [String] = []
var storedArray: [String] = []
    for text in array {

        if storedArray.contains(text) {
             dump(text + " is a duplicate")
             dupliateArray.append(text)
        }
        storedArray.append(text)
    }

Upvotes: 0

Murtas Manuel
Murtas Manuel

Reputation: 13

I don't know how to do that specifically for swift but in general you can check every string of the array with any string after it in the array (just like the sorting algorithm) and if you find that a string is equal to another one then you have a double string in your array

Upvotes: 0

Related Questions