Is there an easy way to remove every nth element from a swift array. For example, in the array below:
thisArray = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]
If n = 3
and start count from first element would like to return:
returnThis = [2.0, 4.0, 1.0, 4.5, 1.2, 3.6, 4.4, 2.0]
Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted. To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.
To do that we will use the array's built-in function called removeAll(). Calling the removeAll() function will remove all elements from an array.
reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.
// swift 4.1:
thisArray.enumerated().compactMap { index, element in index % 3 == 2 ? nil : element }
.enumerated()
to attach the indices.compactMap
to filter out items at indices 2, 5, 8, ... by returning nil
, and strip the index for the rest by returning just element
.(If you are using Swift 4.0 or below, use .flatMap
instead of .compactMap
. The .compactMap
method was introduced in Swift 4.1 by SE-0187)
(If you are stuck with Swift 2, use .enumerate()
instead of .enumerated()
.)
Since the Functional style solutions have already been posted I am using here an old fashion way approach
let nums = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]
var filteredNums = [Double]()
for elm in nums.enumerate() where elm.index % 3 != 2 {
filteredNums.append(elm.element)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With