grouping files of the same extension

The problem is that when you add an element to a slice (that’s inside the map), you have to reassign the result slice, because append() returns a new slice header that contains the appended items:

if val, ok := m[ext]; ok {
   val = append(val, file)
    m[ext] = val
} else {
    // ...

Or simply:

m[ext] = append(m[ext], file)

This also handles if ext is not yet in the map, because then m[ext] will be the zero value of the value type (which is []string), and the zero value is the nil slice. You are allowed to append to the nil slice.

Also to get the extension, use filepath.Ext().

Your group() function can be as simple as this:

func group(names []string) map[string][]string {
    m := map[string][]string{}
    for _, name := range names {
        ext := filepath.Ext(name)
        ext = strings.TrimPrefix(ext, ".")
        m[ext] = append(m[ext], name)
    return m

Testing it:

fmt.Println(group([]string{"x\\a.txt", "b.txt", "c.go"}))

fmt.Println(group([]string{"a.go", "xy\\b.go", "c.txt"}))

Which outputs (try it on the Go Playground):

map[go:[c.go] txt:[x\a.txt b.txt]]
map[go:[a.go xy\b.go] txt:[c.txt]]

See related questions:

How to update map values in Go

How to categorize list of objects based on a parameter

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top