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?
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?
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...)
}
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