Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to loop through array object and group by in golang

Tags:

arrays

go

I have a list of Books (BookId) and each book is associated to a Book collection (CollectionId).

I am trying to figure out the best way to group the results by Collection, so all the books that belong to a collection are listed under it and I can build the results in the following way:

Book A,D,G belong to Collection 1. Book B,C,E belong to Collection 2.

I have the books in a list/array that I need to loop through and look up the collectionID they belong to and them need to store the new lists as seen below:

CollectionID 1:

- Book A, Book D, Book G

CollectionID 2:

- Book B, Book C, Book E

CollectionID 3:

- Book F
like image 417
FutureDroid Avatar asked Dec 23 '22 05:12

FutureDroid


1 Answers

You can use a map to store a slice of books per collection ID.

type Book struct {
    Title        string
    Author       string
    CollectionID int
}

func main() {
    books := GetBooks()
    collections := make(map[int][]Book)
    for _, b := range books {
        collections[b.CollectionID] = append(collections[b.CollectionID], b)
    }
    ...
}
like image 68
Gavin Avatar answered Feb 16 '23 20:02

Gavin