In the following code, I’m creating a two-dimensional array called itemGroups from the values of a dictionary, everything is working as expected except for the items not being alphabetically ordered/sorted.
How can I sort the items in the itemGroups two-dimensional array? Is there a way to do it when calling map()?
class Item{
var name:String = ""
}
var itemGroups: [[Item]] = []
func createGroupsOfItems(){
// dictionary signature just for reference
var dictionaryOfItems:Dictionary = [String: [Item]]()dictionaryOfItems
// add arrays of items from the dictionary values
/// here I need to sort the items within the nested arrays
itemGroups = dictionaryOfItems.keys.sorted().map({ dictionaryOfItems[$0]!})
print("Groups Output: \(sectionsOfItems)") // see output below
print("Dictionary Output: \(sectionForCategory)")// see output below, just for reference
}
Groups output
Groups Output:
[[Item {
name = Zipper;
}, Item {
name = Cup;
}, Item {
name = Apple;
}], [Item {
name = Pizza;
}, Item {
name = Bulb;
}, Item {
name = Avocado;
}]]
Dictionary output
Dictionary Output:
["Group 1": [Item {
name = Zipper;
}, Item {
name = Cup;
}, Item {
name = Apple;
}], "Group 2": [Item {
name = Pizza;
}, Item {
name = Bulb;
}, Item {
name = Avocado;
}]]
Desired Groups output after being sorted
Groups Output:
[[Item {
name = Apple;
}, Item {
name = Cup;
}, Item {
name = Zipper;
}], [Item {
name = Avocado;
}, Item {
name = Bulb;
}, Item {
name = Pizza;
}]]
>Solution :
Simply add sorted to where you pull the [Item] from dictionaryOfItems:
itemGroups = dictionaryOfItems.keys.sorted().map {
dictionaryOfItems[$0]!
.sorted { $0.name > $1.name } // or maybe <
}