I have an array of strings with a large amount of data, only some of which I want. I'm separating the good data using a separator like:
var result = contentArray[1].components(separatedBy: ",")
This leaves me with garbage data in even number indices of the result array, and good data in odd numbered indices.
Now I'm only wanting to work with the good data to make things simple later on. I can do that by creating another array using a for in loop with stride...
But this seems like at least one extra step. Is there a way I can sort the data in the first array without creating 2 arrays? This would have the app creating 3 arrays with large amounts of data when it seems like I should be able to do it in 1 or 2. I'm planning on doing this with a minimum of 20 data sets so that seems a lot of extra arrays in memory
You can go like this.
let filterArray = result.indices.flatMap { $0 % 2 != 0 ? nil : result[$0] }
print(filterArray)
Edit: If you want to store output of filter in same array try like this.
var result = contentArray[1].components(separatedBy: ",")
result = result.indices.flatMap { $0 % 2 != 0 ? nil : result[$0] }
print(result)