Home
Go
Slice Every Nth Element
Updated Aug 4, 2023
Dot Net Perls
Nth element. Consider a slice in Go that contains many elements, but we want to only retain every second or third element. We can develop a special function for this purpose.
Slice
And with an argument, we can specify the interval of elements we want to keep. This function can help when we want to only process some parts of a slice.
func
Example code. This Go program has a custom function called everyNthElement. It only accepts string slices, but this detail can be changed to any other type.
Step 1 In everyNthElement, we create an empty string slice. This is where the "kept" elements are placed.
Step 2 We use a for-range loop over the string slice that was passed in as an argument.
for
range
Step 3 We use a modulo division to determine if we are on the "nth" element we want to keep.
Step 4 We return the result slice. This will contain all the retained elements.
package main import ( "fmt" ) func everyNthElement(values []string, n int) []string { // Step 1: create empty slice. result := []string{} // Step 2: enumerate the input slice. for i, value := range values { // Step 3: if index of element is evenly divisible by n, append it. if i % n == 0 { result = append(result, value) } } // Step 4: return the result slice. return result } func main() { // Use the function on this slice. values := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} result := everyNthElement(values, 2) fmt.Println(result) result = everyNthElement(values, 3) fmt.Println(result) }
[a c e g i] [a d g]
Results. We can see with the argument of 2, every other element is skipped over. And with an argument of 3, we skip over 2 elements between additions to the result.
By implementing an every "nth" element function, we learn about modulo division, enumerating slices, and appending to slices. The nth-element code can be useful in occasional real-world programs.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 4, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen