1

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?

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't follow? In this case you'll have 2 keys each with an array of Items as the value.
My bad, perhaps I shouldn't comment on my phone anymore :p
You could use: dict2[$0.category] = (dict2[$0.category] ?? []) + [$0] to make it shorter though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.