Chris G.
Chris G.

Reputation: 25954

Breakup/split array into smaller arrays

I have an array with a text field being a category
["id", "cat", "item_name"]:

["1", "cat1", "Something"]
["2", "cat2", "Something"]
["3", "cat1", "Something"]
["4", "cat1", "Something"]
["6", "cat1", "Something"]
["7", "cat2", "Something"]
["8", "cat2", "Something"]
["9", "cat2", "Something"]

To be able to use the category in UITableView sections I need to split up the array into smaller arrays - right.

So I need to have:

dic["cat1"][array of items with cat1 in field]()
dic["cat2"][array of items with cat2 in field]()

How would you go about doing that?

Upvotes: 1

Views: 182

Answers (1)

Hugo Tunius
Hugo Tunius

Reputation: 2879

I wouldn't use reduce or map for that. Instead I'd do something like this

var dict: [String: [[String]]] = [:]
arr.forEach() {
    if dict[$0[1]] == nil {
        dict[$0[1]] = []
    }

    dict[$0[1]]?.append($0)
}

However I'd recommend you change your code structure and models to use a struct. So instead of a nested array do the following

struct Item {
    let id: String
    let category: String
    let name: String
} 

Then the code becomes much cleaner and simpler to read

let arr2 = [
    Item(id: "1", category: "cat1", name: "Something"),
    Item(id: "2", category: "cat2", name: "Something"),
    Item(id: "3", category: "cat1", name: "Something")
]
var dict2: [String: [Item]] = [:]
arr2.forEach() {
    if dict2[$0.category] == nil {
        dict2[$0.category] = []
    }

    dict2[$0.category]?.append($0)
}

Upvotes: 2

Related Questions