0

I have an array of objects:

struct Person {
    let name: String
    let dateOfBirth: Date
    let money: Double
}

It contains people and how much money they have received or spent. The array contains 54 such objects. I need to find all objects with the same name and date fields and sum their money. That is, in the end, I have to get less than 54 records in my array.

Example: In the array, there are 3 records with the object John. For example, first, he received $15.0, then spent $7.0, and then received $4.0. For my task, I need to have 1 record in the array instead of 3 (with money filed as $12.0)

Does anyone have any idea?

2
  • (offtopic) I really recommend to represent money values with Decimal not with a Double, otherwise you will start losing precision when summing values. Commented Jul 27, 2017 at 14:20
  • @Sulthan, thanks for the advice, but it is just an example, I do not use it Commented Aug 2, 2017 at 9:38

2 Answers 2

2

You can loop through the array and add them to a dictionary, where the name concatenated with the date of birth will be the key and the sum of the money will be the value.

Assuming your array containing Person objects is called people:

var moneyDictionary = [String:Double]()
for person in people {
    let personKey = "\(person.name)\(person.dateOfBirth)"
    if let personRecord = moneyDictionary[personKey] {
        moneyDictionary[personKey] = personRecord + person.money
    } else {
        moneyDictionary[personKey] = person.money
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe something like this would work:

struct Person {
    let name: String
    let dateOfBirth: Date
    let money: Double
}

let currentDate = Date()
let person = Person(name: "James", dateOfBirth: currentDate, money: 15)
let person1 = Person(name: "James", dateOfBirth: currentDate, money: -7)
let person2 = Person(name: "James", dateOfBirth: currentDate, money: 4)

// array of person objects
let personArray = [person, person1, person2]

// selected person
let selectedPerson = person

// filter with selected person only
var matchingPersons = personArray.filter {
    $0.name == selectedPerson.name && $0.dateOfBirth == selectedPerson.dateOfBirth
}

// extract values
var values = matchingPersons.map { $0.money }

// total
var total = values.reduce(0, +)

2 Comments

By the way, you can compare Date instances simply by ==.
Updated my answer with regards to @Sulthan comment 👍🏼

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.