Home > front end >  How to sort items within a two dimensional array
How to sort items within a two dimensional array

Time:12-19

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

CodePudding user response:

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

CodePudding user response:

To change the values of a dictionary in a map kind of way, use (wait for it)... mapValues!

Suppose we have this:

class Item: CustomStringConvertible {
    var name: String = ""
    init(name: String) { self.name = name }
    var description: String { name }
}

And suppose we form this dictionary:

    dict = ["Group 1": [Item(
        name: "Zipper"
    ), Item(
        name: "Cup"
    ), Item(
        name: "Apple"

    )], "Group 2": [Item(
        name: "Pizza"
    ), Item(
        name: "Bulb"
    ), Item(
        name: "Avocado"
    )]]

Then the sorted dictionary is

    let dictSorted = dict.mapValues{ $0.sorted { $0.name < $1.name} }
    // ["Group 1": [Apple, Cup, Zipper], "Group 2": [Avocado, Bulb, Pizza]]
  • Related