How to find sum for each category in an array?

孤者浪人 提交于 2021-01-29 20:22:27

问题


I have an array that contains multiple items. This is a Realm array. It contains data in the following structure:

Results<Entry> <0x7ff04840e1a0> (
    [0] Entry {
        name = Salary;
        amount = 40000;
        date = 2020-03-18 16:00:00 +0000;
        category = Main Incomes;
        entryType = Income;
    },
    [1] Entry {
        name = Diff;
        amount = -500;
        date = 2020-04-18 16:00:00 +0000;
        category = Misc;
        entryType = Expense;
    },
    [2] Entry {
        name = Cat Food;
        amount = -399;
        date = 2020-04-18 16:00:00 +0000;
        category = Animals;
        entryType = Expense;
    },
    [3] Entry {
        name = Fish Food;
        amount = -599;
        date = 2020-04-18 16:00:00 +0000;
        category = Animals;
        entryType = Expense;
    }
)

What I am trying to achieve is to make another array that will 'pivot' totals for each category. So it can work as a pivot table in Excel.

The desired output is an array that will contain totals for each category:

[0] X-Array {
        category = Main Incomes;
        amount = XXXX;
    },
    [1] X-Array {
        category = Animals;
        amount = XXXX;

And so on...

I'm fairly new to this fancy one-liners like .map and .reduce and other Swift's array management sugar, so would very much appreciate the advice!

Thank you!

P.S. I plan to do the same thing with total expenses and incomes in order to calculate closing balance.


回答1:


I think use Dictionary is easier to do categorize and later you can convert it to array or anything you want

var dict:[String:Double] = [:]

list.forEach {
    if let current = dict[$0.category]{
        dict[$0.category] = current + $0.amount
    }else{
        dict[$0.category] = $0.amount
    }
}

print(dict)



回答2:


I think the question is asking how to get the sum for each category, Income, Expense etc. If so, here's how it's done using the .sum function on the results.

let totalIncome = realm.objects(AccountClass.self)
                       .filter("entryType == 'Income'")
                       .sum(ofProperty: "amount") as Int
let totalExpense = realm.objects(AccountClass.self)
                        .filter("entryType == 'Expense'")
                        .sum(ofProperty: "amount") as Int

print("Total Income: \(totalIncome)")
print("Total Expense: \(totalExpense)")

and the output for your example data is

Total Income: 40000
Total Expense: 1498

If you want a pivot table, you could just add the amounts to an array - if you need the labels, use a tuple to store them in an array like this

let i = ("Income", totalIncome)
let e = ("Expense", totalExpense)

let tupleArray = [i, e]

for account in tupleArray {
   print(account.0, account.1)
}

Keep in mind that a Results object is not an array but has some array-like functions. Results are live updating so as the underlying data in Realm changes, the Results change along with it.



来源:https://stackoverflow.com/questions/61302639/how-to-find-sum-for-each-category-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!