-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]]

1
  • 2
    Your "result" makes no sense. What if three Persons have "name1" and two other Persons have "name2"? Now what output do you expect? Commented Jul 7, 2016 at 20:23

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 Persons. I think having the array of Persons would be better than just the count of them.
@Putz1103: yes because 2 Person(s) with the same name could have different secondName(s)
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.