Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by slice fields

Tags:

go

I have the following Structs:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

I have made a slice of Parents with the following values:

parents := make([]Parent, 0)

p1 := Parent {
    "3",
    []Child {
        {"2"},
        {"3"},
        {"1"},
    },
}

p2 := Parent {
    "1",
    []Child {
        {"8"},
        {"9"},
        {"7"},
    },
}

p3 := Parent {
    "2",
    []Child {
        {"5"},
        {"6"},
        {"4"},
    },
}             

parents = append(parents, p1, p2, p3)

I am trying to sort the "parents" slice in the following order:

1) First, sort all Parents by Parent.id

2) Next, sort each Parent's "children" slice by Child.id

The expected result is something like:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]

Is there a way to do this in Go?

like image 942
Floating Sunfish Avatar asked Apr 10 '17 06:04

Floating Sunfish


People also ask

How do you sort a slice?

Use the function sort. Slice . It sorts a slice using a provided function less(i, j int) bool . To sort the slice while keeping the original order of equal elements, use sort.

How does sort slice work in Golang?

In Go language, you can sort a slice with the help of Slice() function. This function sorts the specified slice given the provided less function. The result of this function is not stable. So for stable sort, you can use SliceStable.


1 Answers

I got it to work using the following code:

// sort each Parent in the parents slice by Id
sort.Slice(parents, func(i, j int) bool {return parents[i].id < parents[j].id})

// for each Parent, sort each Child in the children slice by Id
for _, parent := range parents {
    sort.Slice(parent.children, func(i, j int) bool {return parent.children[i].id < parent.children[j].id})
}

Special thanks to @Volker for mentioning the sort.Slice function! I had no idea it existed!

like image 97
Floating Sunfish Avatar answered Oct 23 '22 05:10

Floating Sunfish