To filter elements of an array based on a condition in Go, you can use a loop to iterate through the array and a conditional statement to check each element against the specified condition.
In this example,
filterEvenNumbers
that takes an integer slice arr
as a parameter.result
to store the filtered elements.arr
.if
statement to check if the current element is even (i.e., num % 2 == 0
).result
slice.result
slice containing only the even numbers.main
function, we call the filterEvenNumbers
function with a sample array and print the filtered result.package main
import "fmt"
func filterEvenNumbers(arr []int) []int {
result := []int{}
for _, num := range arr {
if num % 2 == 0 {
result = append(result, num)
}
}
return result
}
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evenNumbers := filterEvenNumbers(arr)
fmt.Println("Filtered even numbers:", evenNumbers)
}
Filtered even numbers: [2 4 6 8 10]
In this example,
filterStringsContaining
that takes a slice of strings arr
and a substring substr
as parameters.result
to store the filtered elements.arr
.if
statement with the strings.Contains
function to check if the current element contains the specified substring.result
slice.result
slice containing only the strings that include the substring.main
function, we call the filterStringsContaining
function with a sample array and substring, then print the filtered result.package main
import (
"fmt"
"strings"
)
func filterStringsContaining(arr []string, substr string) []string {
result := []string{}
for _, str := range arr {
if strings.Contains(str, substr) {
result = append(result, str)
}
}
return result
}
func main() {
arr := []string{"apple", "banana", "cherry", "date", "fig", "grape"}
filteredStrings := filterStringsContaining(arr, "a")
fmt.Println("Filtered strings containing 'a':", filteredStrings)
}
Filtered strings containing 'a': [apple banana date grape]
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Go language with well detailed examples.