How to Filter Elements of an Array based on a Condition in Go - Step by Step Examples



How to Filter Elements of an Array based on a Condition in Go ?

Answer

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.



✐ Examples

1 Filter Even Numbers from an Integer Array

In this example,

  1. We define a function named filterEvenNumbers that takes an integer slice arr as a parameter.
  2. Inside the function, we create a new slice result to store the filtered elements.
  3. We use a loop to iterate through each element in the array arr.
  4. Within the loop, we use an if statement to check if the current element is even (i.e., num % 2 == 0).
  5. If the condition is met, we append the element to the result slice.
  6. After the loop completes, we return the result slice containing only the even numbers.
  7. In the main function, we call the filterEvenNumbers function with a sample array and print the filtered result.

Go Program

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

Output

Filtered even numbers: [2 4 6 8 10]

2 Filter Strings Containing a Specific Substring

In this example,

  1. We define a function named filterStringsContaining that takes a slice of strings arr and a substring substr as parameters.
  2. Inside the function, we create a new slice result to store the filtered elements.
  3. We use a loop to iterate through each element in the array arr.
  4. Within the loop, we use an if statement with the strings.Contains function to check if the current element contains the specified substring.
  5. If the condition is met, we append the element to the result slice.
  6. After the loop completes, we return the result slice containing only the strings that include the substring.
  7. In the main function, we call the filterStringsContaining function with a sample array and substring, then print the filtered result.

Go Program

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

Output

Filtered strings containing 'a': [apple banana date grape]

Summary

In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Go language with well detailed examples.




More Go Arrays Tutorials

  1. How to Declare an Array in Go ?
  2. How to Initialize an Array in Go ?
  3. How to Access Array Elements in Go ?
  4. How to Access Array Elements using Index in Go ?
  5. How to get First Element in Array in Go ?
  6. How to get Last Element in Array in Go ?
  7. How to check if an Array is Empty in Go ?
  8. How to check if an Array is Not Empty in Go ?
  9. How to get Sub Array in Go ?
  10. How to Get Array Length in Go ?
  11. How to Iterate Over an Array in Go ?
  12. How to Iterate Over an Array in Reverse Order in Go ?
  13. How to get the Index of Specified Element in an Array in Go ?
  14. How to check if Specified Element is present in the Array in Go ?
  15. How to count the Number of Occurrences of Specified Element in the Array in Go ?
  16. How to Sort an Array in Go ?
  17. How to Sort an Array in Ascending Order in Go ?
  18. How to Sort an Array in Descending Order in Go ?
  19. How to create a Two Dimensional Array in Go ?
  20. How to Iterate over a Two Dimensional Array in Go ?
  21. How to create a Three Dimensional Array in Go ?
  22. How to Copy an Array in Go ?
  23. How to Split an Array in Go ?
  24. How to Join Arrays in Go ?
  25. How to check if Two Arrays are Equal in Go ?
  26. How to check if Two Arrays have Same Elements (Regardless of Order) in Go ?
  27. How to Convert an Array of Integers to an Array of Strings in Go ?
  28. How to Convert an Array of Strings to an Array of Integers in Go ?
  29. How to Reverse an Array in Go ?
  30. How to Shuffle an Array in Go ?
  31. How to Rotate Elements in an Array in Go ?
  32. How to Filter Elements of an Array based on a Condition in Go ?
  33. How to Declare an Integer Array in Go ?
  34. How to Declare a Float Array in Go ?
  35. How to Declare a String Array in Go ?
  36. How to Remove Duplicates in an Array in Go ?
  37. How to Remove Specific Element from an Array in Go ?
  38. How to Remove Element from Array based on a Condition in Go ?
  39. How to Sort a String Array in Dictionary Order in Go ?
  40. How to Concatenate Strings in Array in Go ?