gentilmente
gentilmente

Reputation: 73

How to flatten a 2D slice into 1D slice?

I have

arr := [][]int32 {{1,2,3} ,{4,5,6}, {7,8,9}}

and I want

newArr := []int32 {1,2,3,4,5,6,7,8,9}

In JS I can do

arr1d = [].concat(...arr2d);

as one of many simple ways like this

Is there in Go something like this?

Upvotes: 4

Views: 4330

Answers (4)

Michael Tadnir
Michael Tadnir

Reputation: 121

Go 1.22

As said by @Mart, There's a library function for that, example usage:

w := [][]string{{"a", "b", "c"}, {"d", "e", "f"}}
v := slices.Concat(w...)
fmt.Println(v) // [a b c d e f]

see - https://pkg.go.dev/[email protected]#Concat

Upvotes: 0

Mart
Mart

Reputation: 101

As predicted by Eli Bendersky, from Go 1.22 you have slices.Concat

Upvotes: 2

blackgreen
blackgreen

Reputation: 45081

Go 1.18

You can't avoid a for loop, but with generics this is easily extensible to slices of any type:

func Flatten[T any](lists [][]T) []T {
    var res []T
    for _, list := range lists {
        res = append(res, list...)
    }
    return res
}

Example usage:

func main() {
    w := [][]string{{"a", "b", "c"}, {"d", "e", "f"}}
    v := Flatten(w)
    fmt.Println(v) // [a b c d e f]

    d := [][]uint64{{100, 200}, {3000, 4000}}
    e := Flatten(d)
    fmt.Println(e) // [100 200 3000 4000]
}

Playground: https://go.dev/play/p/X81g7GYFd4n

Upvotes: 3

Eli Bendersky
Eli Bendersky

Reputation: 273696

Go has strings.Join and bytes.Join, but no generic functionality to join/concat a slice. It's possible that once generics are introduced into the language such functionality will be added to the standard library.

In the meantime, doing this with a loop is clear and concise enough.

var newArr []int32
for _, a := range arr {
  newArr = append(newArr, a...)
}

Upvotes: 4

Related Questions