Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove Every Other Element in an Array in Swift?

Tags:

arrays

swift

So say I have an array:

var stringArray = ["a","b","c","d","e","f","g","h","i","j"]

Now, how do I delete "a", "c", "e", "g", and "i" (all the even number indexes from the array)?

Thanks!

like image 872
Sunay Avatar asked Mar 14 '16 02:03

Sunay


People also ask

How do I remove every second element from an array?

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.

How do I clear an array in Swiftui?

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.


1 Answers

Instead of using C-style for-loops (which are set to be deprecated in an upcoming version of Swift), you could accomplish this using strides:

var result = [String]()
for i in stride(from: 1, through: stringArray.count - 1, by: 2) {
    result.append(stringArray[i])
}

Or for an even more functional solution,

let result = stride(from: 1, to: stringArray.count - 1, by: 2).map { stringArray[$0] }
like image 66
colavitam Avatar answered Sep 21 '22 21:09

colavitam