Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort items within a two dimensional array

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;
}]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 <
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading