How do you sort an array of dictionaries?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SamuelMb

This is a representation of what my array might look like:

array = [
{name: "Jack", age: 21}
{name: "Jill", age: 17}
{name: "Tom", age: 56}
]

So, what if I want to sort this array based on the age label of each dictionary in the array? How would I go about doing that?

I looked up the sort() function but it returns null so I suspect I might be using it wrong. I also looked up the custom_sort function but it also returns null. Any guidance would be appreciated.

Edit: Never mind. I figured it out. This is how you do it:

array.sort_custom(MyCustomSorter, "sort")

class MyCustomSorter:
    static func sort(a, b):
        if a["Age"] < b["Age"]:
            return true
        return false

are it as an answer and mark it so it will be easier for people to find the answer

rustyStriker | 2019-12-27 12:28

Sure thing. Just did.

SamuelMb | 2019-12-27 12:47

:bust_in_silhouette: Reply From: SamuelMb

Edit: Never mind. I figured it out. This is how you do it:

array.sort_custom(MyCustomSorter, "sort")

class MyCustomSorter:
    static func sort(a, b):
        if a["Age"] < b["Age"]:
            return true
        return false

For others: Here is the documentation for Array.sort_custom(func)

st_phan | 2023-03-24 21:54