Array Every Nth Element
This page was last reviewed on Aug 9, 2023.
Dot Net Perls
Nth element. In Swift 5.8 we can develop a function that loops over an array, and return an array of elements at certain indexes. We can return every nth element this way.
With modulo division, we can test the indexes of an array. Calling enumerated() on the array allows us to elegantly access indexes and values.
To begin, we introduce an everyNthElement function. This version operates on a String array, but it could be easily changed to use another element type.
Step 1 We create an empty String array—this is where we will store the results as we encounter them.
Step 2 We loop over the input array with enumerated(), and test all the indexes with modulo division.
Step 3 We return the result array, which now is populated with every nth element from the input array.
func everyNthElement(array: [String], n: Int) -> [String] { // Step 1: create result array. var result = [String]() // Step 2: loop over array, and if index is evenly divisible by n, append it. for (index, value) in array.enumerated() { if index % n == 0 { result.append(value) } } // Step 3: return result array. return result } // Use the function on this array. var test = [String](arrayLiteral: "a", "b", "c", "d", "e", "f", "g", "h", "i") var result = everyNthElement(array: test, n: 2) print(result) var result2 = everyNthElement(array: test, n: 3) print(result2)
["a", "c", "e", "g", "i"] ["a", "d", "g"]
Results. It is easy to see that the function returns the correct results, just by checking the input array and the output. With an argument of 2, it skips every other element.
Summary. With modulo division, we can test for elements in an array that are a certain distance apart. And by calling append() on an empty array, we can place these elements in a new collection.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 9, 2023 (new).
© 2007-2024 Sam Allen.