Go - sort by multiple fields example

In this example, we will show you how to sort by multiple fields in Golang with an example.

In Golang, Data can be sorted by multiple criteria.

Go - sort by multiple fields example - In ascending order

In the example, we sort a slice of students by score and when the score is the same, by name. In ascending order:


package main

import (
    "fmt"
    "sort"
)

type Student struct {
    name  string
    score int
}

func main() {

    students := []Student{

        Student{name: "John", score: 77},
        Student{name: "Tony", score: 88},
        Student{name: "Tom", score: 94},
        Student{name: "Bruce", score: 98},
        Student{name: "Jony", score: 87},
        Student{name: "Ricky", score: 87},
        Student{name: "Net", score: 91},
        Student{name: "Raj", score: 68},
        Student{name: "Amir", score: 71},
        Student{name: "Arun", score: 87},
    }

    sort.Slice(students, func(i, j int) bool {

        if students[i].score != students[j].score {
            return students[i].score < students[j].score
        }

        return students[i].name < students[j].name
    })

    fmt.Println(students)
}

Output:

[{Raj 68} {Amir 71} {John 77} {Arun 87} {Jony 87} {Ricky 87} {Tony 88} {Net 91} {Tom 94} {Bruce 98}]

Go - sort by multiple fields example - In descending order

In the example, we sort a slice of students by score and when the score is the same, by name. In descending order:


package main

import (
    "fmt"
    "sort"
)

type Student struct {
    name  string
    score int
}

func main() {

    students := []Student{

        Student{name: "John", score: 77},
        Student{name: "Tony", score: 88},
        Student{name: "Tom", score: 94},
        Student{name: "Bruce", score: 98},
        Student{name: "Jony", score: 87},
        Student{name: "Ricky", score: 87},
        Student{name: "Net", score: 91},
        Student{name: "Raj", score: 68},
        Student{name: "Amir", score: 71},
        Student{name: "Arun", score: 87},
    }

    sort.Slice(students, func(i, j int) bool {

        if students[i].score != students[j].score {
            return students[i].score > students[j].score
        }

        return students[i].name > students[j].name
    })

    fmt.Println(students)
}

Output:

[{Bruce 98} {Tom 94} {Net 91} {Tony 88} {Ricky 87} {Jony 87} {Arun 87} {John 77} {Amir 71} {Raj 68}]

Comments