Start learning free

LESSON 167 OF 404 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 - Group by Category in Go

Practice

Use a map to accumulate totals per category while looping over parallel slices, then list the categories sorted by name.

You start with:

items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
prices := []int{2, 3, 25, 1, 40}
categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}

Build:

Clothes: $65
Food: $6

Rules:

  • Build a map totals that maps each category to the sum of the prices of its items.
  • Loop with an index. For each item, add its price to the total of categories[i]; a category you have not seen yet counts as 0.
  • Make one line per category, in the format "Category: $total", sorted alphabetically by category name (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with fmt.Println(result).

A map gives 0 for a missing key, so totals[cat] = totals[cat] + prices[i] just works.

Collect the keys into a slice and call sort.Strings(keys) before building the lines.

items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
prices := []int{2, 3, 25, 1, 40}
categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}

totals := map[string]int{}
for i := range items {
    cat := categories[i]
    totals[cat] = totals[cat] + prices[i]
}
lines := []string{}
keys := make([]string, 0, len(totals))
for cat := range totals {
    keys = append(keys, cat)
}
sort.Strings(keys)
for _, cat := range keys {
    lines = append(lines, cat + ": $" + strconv.Itoa(totals[cat]))
}
result := strings.Join(lines, "\n")
fmt.Println(result)

STEP 1 OF 13
    Ctrl + Enter to check

    Shopping Cart V6 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free