In Go, you can use a combination of slice operations and a loop to remove elements from an array based on a condition.
In this example,
package main
import (
"fmt"
)
func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
oddNumbers := []int{}
for _, num := range numbers {
if num % 2 != 0 {
oddNumbers = append(oddNumbers, num)
}
}
fmt.Println("Slice after filtering:", oddNumbers)
}
Slice after filtering: [1 3 5 7 9]
In this example,
package main
import (
"fmt"
"strings"
)
func main() {
words := []string{"apple", "banana", "grape", "orange", "melon"}
filteredWords := []string{}
for _, word := range words {
if !strings.Contains(word, "a") {
filteredWords = append(filteredWords, word)
}
}
fmt.Println("Slice after filtering:", filteredWords)
}
Slice after filtering: [melon]
In this tutorial, we learned How to Remove Element from Array based on a Condition in Go language with well detailed examples.