按数组值分组数组

时间:2019-07-12 04:24:12

标签: arrays swift

我有很多数组,我想按数组值对该数组进行分组。如何使脚本功能为此分组数组?

我有如下数组

["TODAY","TODAY","MONDAY","MONDAY","TUESDAY","TUESDAY","SUNDAY"]
["Angela","Hane","Amel","JOHN","Joseph","Dickinson","RICK"]
["DEV","PRO","ADMIN","PRO","ADMIN","DEV","PRO"]

我想分组成为一个新数组

[TODAY,MONDAY,TUESDAY,SUNDAY]
//depends by days
[
    [//today
        [Angela,Hane]
        [DEV,PRO]

    ],

    [//monday
        [Amel,JOHN]
        [ADMIN,PRO]
    ],

    [//tuesday
        [Joseph,Dickinson]
        [ADMIN,DEV]
    ]
    [//sunday
        [RICK]
        [PRO]
    ]
]

迅速

let days = [TODAY,TODAY,MONDAY,MONDAY,TUESDAY,TUESDAY,SUNDAY]
let arr1 = [Angela,Hane,Amel,JOHN,Joseph,Dickinson,RICK]
let arr2 = [DEV,PRO,ADMIN,PRO,ADMIN,DEV,PRO]



//depends on days

let items = [
    [//today
        [Angela,Hane]
        [DEV,PRO]

    ],

    [//monday
        [Amel,JOHN]
        [ADMIN,PRO]
    ],

    [//tuesday
        [Joseph,Dickinson]
        [ADMIN,DEV]
    ]
    [//sunday
        [RICK]
        [PRO]
    ]
]

我需要此数组分组以使用标题在表视图中显示..请帮助我创建一个脚本来生成此数组。

感谢您的帮助。

我很感激。

2 个答案:

答案 0 :(得分:1)

重构设计。而不是使用多个数组,而是使用struct

struct Person {
    let name, weekday, type : String
}

let items = [Person(name: "Angela", weekday: "TODAY", type: "DEV"),
             Person(name: "Hane", weekday: "TODAY", type: "PRO"),
             Person(name: "Amel", weekday: "MONDAY", type: "ADMIN"),
             Person(name: "JOHN", weekday: "MONDAY", type: "PRO"),
             Person(name: "Joseph", weekday: "TUESDAY", type: "ADMIN"),
             Person(name: "Dickinson", weekday: "TUESDAY", type: "DEV"),
             Person(name: "RICK", weekday: "SUNDAY", type: "PRO")]

然后您就可以轻松地将它们分组

let groupedItems = Dictionary(grouping: items, by: {$0.weekday})

要显示项目,请获取键(您可以添加逻辑以对其进行排序)

let keys = Array(groupedItems.keys)

并通过键获取相应的值

let section = keys[indexPath.section]
let people = groupedItems[section]!
let row = people[indexPath.row]

答案 1 :(得分:0)

这里是使用3个单独的arrays解决当前代码问题的方法。

首先,您可以使用 zip(_:_:) 从所有三个array中组合得到一个arrays

let days = ["TODAY","TODAY","MONDAY","MONDAY","TUESDAY","TUESDAY","SUNDAY"]
let arr1 = ["Angela","Hane","Amel","JOHN","Joseph","Dickinson","RICK"]
let arr2 = ["DEV","PRO","ADMIN","PRO","ADMIN","DEV","PRO"]

let arr = Array(zip(days, zip(arr1, arr2))) 

现在,使用{p>来基于arrday进行分组,

let grouped = Dictionary(grouping: arr, by: {$0.0})

此外,您可以使用grouped来基于days来获取数据,

let values = grouped[days[indexPath.row]]

注意:与其创建3个单独的arrays,不如创建一个struct/class类型,并使用它来表示所有数据。