4

I have an Array of Transaction objects

var returnedArray: Array<Transaction> = [a, b, c, d]

One of the properties of Transaction is an NSDate. I want to convert my Array into a Dictionary

var transactions: [NSDate: Array<Transaction>]

Where all the transactions on that date will be in an Array that has the date as the key.

I know how to loop through each element of my array and manually assign it to the right key but i'm wondering if there is an elegant function to do that.

Mika
  • 5,807
  • 6
  • 38
  • 83

2 Answers2

2

I'm typing this in the dark as you haven't provided a lot of details in your question. You need to improvise:

// Get the list of distinct dates
var dates = [NSDate]()
for tran in returnedArray {
    if !dates.contains(tran.transactionDate) {
        dates.append(tran.transactionDate)
    }
}

// Now group according to date
var result = [NSDate : Array<Transaction>]()
for d in dates {
    let transactions = returnedArray.filter { $0.transactionDate == d } 
    result[d] = transactions
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
2

The dates form a set

var setOfDates = Set (returnedArray.map (transDate))

You can create a dictionary from a sequence of pairs:

var result = Dictionary (dictionaryLiteral: setOfDates.map { 
    (date:NSDate) in
  return (date, returnedArray.filter { date == $0.transDate })
}

You could define this as an array extension. Something like:

extension Array {
  func splitBy<Key:Hashable> (keyMaker: (T) -> Key) -> Dictionary<Key, T> {
    let theSet = Set (self.map (keyMaker))
    return Dictionary (dictionaryLiteral: theSet.map { (key:Key) in 
       return (key, self.filter { key == keyMaker($0) })
    })
  }
}
GoZoner
  • 67,920
  • 20
  • 95
  • 145