如何找到数组中每个类别的总和? [英] How to find sum for each category in an array?

查看:56
本文介绍了如何找到数组中每个类别的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个项目的数组.这是一个Realm数组.它包含以下结构的数据:

  Results< Entry>< 0x7ff04840e1a0>([0]条目{名称=薪水;数量= 40000;日期= 2020-03-18 16:00:00 +0000;类别=主要收入;entryType =收入;},[1]条目{名称= Diff;数量= -500;日期= 2020-04-18 16:00:00 +0000;类别=杂项;entryType =费用;},[2]条目{名称=猫粮;金额= -399;日期= 2020-04-18 16:00:00 +0000;类别=动物;entryType =费用;},[3]条目{名称=鱼食;金额= -599;日期= 2020-04-18 16:00:00 +0000;类别=动物;entryType =费用;}) 

我要实现的目标是制作另一个数组,该数组将枢轴化"每个类别的总计.因此它可以用作Excel中的数据透视表.

所需的输出是一个数组,其中将包含每个类别的总数:

  [0] X-Array {类别=主要收入;金额= XXXX;},[1] X-Array {类别=动物;金额= XXXX;等等... 

我对于像 .map .reduce 以及其他Swift的数组管理工具这样的奇特的一线工具还是很陌生的,所以非常感谢您的建议!/p>

谢谢!

P.S.我计划对总支出和收入执行相同的操作,以便计算期末余额.

解决方案

我认为使用Dictionary更容易进行分类,以后您可以将其转换为数组或所需的任何内容

  var dict:[String:Double] = [:]list.forEach {如果让current = dict [$ 0.category] ​​{dict [$ 0.category] ​​=当前+ $ 0.amount}别的{dict [$ 0.category] ​​= $ 0.amount}}打印(dict) 

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.

解决方案

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)

这篇关于如何找到数组中每个类别的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆