-1

I want to create array of unique elements by specific property.

Ex:

I have array of objects (Person) :

struct Person {
    var name: String?
    var secondName: String?

    init (name: String, secondName: String) {

        self.name = name
        self.secondName = secondName
    }
}

let person1 = Person(name: "name1", secondName: "secondName1")
let person2 = Person(name: "name2", secondName: "secondName2")
let person3 = Person(name: "name1", secondName: "secondName3")

let personsArray = [person1, person2, person3]

I want to get new array, that will contain person objects with unique name

something like this $0.name == $1.name

What is the best way to achieve that ?


Result should be arrays of objects with unique name param = [[person1, person3], [person2]]

jscs
  • 63,694
  • 13
  • 151
  • 195
Vlad Z.
  • 3,401
  • 3
  • 32
  • 60
  • 2
    Your "result" makes no sense. What if three Persons have "name1" and two other Persons have "name2"? Now what output do you expect? – matt Jul 07 '16 at 20:23

2 Answers2

1

This is my personal interpretation of your question

Given an array of Person(s) you want in output several dictionaries where the key is the name of a person and the value is a list of persons with that name.

Here's the code

let dict = persons.reduce([String:[Person]]()) { (dict, person) -> [String:[Person]] in
    var dict = dict
    dict[person.name] = (dict[person.name] ?? []) + [person]
    return dict
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • That's a good method. I just finished writing up a set of code that creates a dictionary with an int value as the value instead of an array of `Person`s. I think having the array of `Person`s would be better than just the count of them. – Putz1103 Jul 07 '16 at 20:36
  • @Putz1103: yes because 2 `Person(s)` with the same `name` could have different `secondName(s)` – Luca Angeletti Jul 07 '16 at 20:38
1

One approach: You could add them one by one to a dictionary where "name" is the key (consider using lowercase for it), and "array of Persons" is the value. When done, the keys array will have all your unique "name" values, and each key's value will be the array of Persons with that "name". You could then "trim" your dictionary by removing any key with an array that has a count less than 2.

Alternative: Sort the array by "name", then you can easily remove any that don't appear twice (if an element doesn't match one of it's neighbors, then remove it).

ghostatron
  • 2,620
  • 23
  • 27