1. Basic pattern
func flattenList(input []any) []any {
res := []any{}
for _, v := range input {
if nest, ok := v.([]any); ok {
res = append(res, flattenList(nest)...)
} else {
res = append(res, v)
}
}
return res
}
2. Flatten list to nth level(n=0,1,…), and starts with start
// flattenList flats the list to nth level starts with 0
func flattenListWithLevel(input []any, n int, start int) []any {
res := []any{}
for _, v := range input {
if nest, ok := v.([]any); ok && start < n {
res = append(res, flattenList(nest, n, start+1)...)
} else {
res = append(res, v)
}
}
return res
}
Related