flatten array after removing `nil` if any; if array is all nil, return empty array. in go

Here's a simple function in Go to flatten an array by removing the nil values:

main.go
package main

import (
	"fmt"
)

func FlattenArray(arr []interface{}) []interface{} {
	flattened := []interface{}{}
	for _, element := range arr {
		if element != nil {
			flattened = append(flattened, element)
		}
	}
	return flattened
}

func main() {
	arr := []interface{}{1, 2, nil, 3, nil, 4}
	fmt.Println(FlattenArray(arr)) // Output: [1 2 3 4]

	arr2 := []interface{}{nil, nil, nil}
	fmt.Println(FlattenArray(arr2)) // Output: []

	arr3 := []interface{}{}
	fmt.Println(FlattenArray(arr3)) // Output: []
}
511 chars
27 lines

In the FlattenArray function, we iterate over each element of the input array arr and check if it is nil or not. If the element is not nil, we append it to the flattened slice. Finally, we return the flattened slice.

Note that we are using the interface{} type to handle any kind of elements in the array, including nil values.

related categories

gistlibby LogSnag