Y
Y
Yuri2021-12-22 10:28:58
Swift
Yuri, 2021-12-22 10:28:58

How to convert realm array to multidimensional dynamic?

There is an array obtained from the realm database:
var spendingArray: Results<Spending>!

Spending table structure in the realm database:

class Spending: Object {
    
    @objc dynamic var category = ""
    @objc dynamic var sum: Int = 1
    @objc dynamic var day : Int = 1


How to convert it to a multidimensional array like:
[array] = [array of days[array day1 [arrays of categories, arrays of sums]]]

Given that days can repeat.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
briahas, 2021-12-22
@briahas

try it, in the online playground it seems to have worked out the norms.
You can play around with the DaySection init - instead of cell, pass an array at once (if it's more convenient for you).
Well, and if this is not what you need - specify.

spoiler
import Foundation

class Spending {
    let category: String
    let sum: Int
    let day: Int

    init(category: String, sum: Int, day: Int) {
        self.category = category
        self.sum = sum
        self.day = day
    }
}

struct CellData {
  let category: String
  let sum: Int
}
class DaySection {
    var cells = [CellData]()
    let day: Int

    init(day: Int, cell: CellData) {
        self.cells.append(cell)
        self.day = day
    }
}

var destArr = [DaySection]()
var sourceArr = [Spending]()
sourceArr.append(Spending(category:"1", sum:1, day:1))
sourceArr.append(Spending(category:"2", sum:2, day:1))
sourceArr.append(Spending(category:"1", sum:1, day:2))
sourceArr.append(Spending(category:"2", sum:2, day:2))
sourceArr.append(Spending(category:"1", sum:1, day:3))

destArr = sourceArr.reduce([DaySection](), { (aggr, elem) in
  let newCell = CellData(category: elem.category, sum: elem.sum)
  guard let day = aggr.first(where: {$0.day == elem.day}) 
      else {
        var temp = aggr
        let newDaySection = DaySection(day: elem.day, cell: newCell)
        temp.append(newDaySection)
        return temp
      }
  
  day.cells.append(newCell)
  return aggr
})
</spoiler>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question