"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort a Slice of Structs by Multiple Fields in Go?

How to Sort a Slice of Structs by Multiple Fields in Go?

Published on 2024-11-15
Browse:613

How to Sort a Slice of Structs by Multiple Fields in Go?

Sorting Slice Objects by Multiple Fields

Sorting by Multiple Criteria

Consider the following Parent and Child structs:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

Suppose we have a slice of Parent structs with predefined values:

parents := []Parent{
    {
        "3",
        []Child{
            {"2"},
            {"3"},
            {"1"},
        },
    },
    {
        "1",
        []Child{
            {"8"},
            {"9"},
            {"7"},
        },
    },
    {
        "2",
        []Child{
            {"5"},
            {"6"},
            {"4"},
        },
    },
}

Sorting Requirements:

Our goal is to sort the parents slice based on two criteria:

  1. Sort Parent structs in ascending order of their id field.
  2. Within each Parent struct, sort the children slice in ascending order of the id field.

Solution:

To achieve this sorting, we utilize the sort.Slice function, which provides a flexible way to sort slices based on custom comparison functions. Here's the code:

// Sort parents by their ID
sort.Slice(parents, func(i, j int) bool { return parents[i].id 

This sorting algorithm efficiently handles both criteria, ensuring that the parents slice is ordered as desired.

Expected Result:

The sorted slice should resemble the following structure:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3