user3110353
user3110353

Reputation: 522

Swift Append every second item to Array

I have a swift array "Monthdata" that I want to append every second value in my months array.

var monthData = []
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]

for month in months {
 self.monthData.append(month)
}

So basically I the monthData array to look like:

["Aug 12","Oct 12"]

Upvotes: 6

Views: 4578

Answers (5)

Andrew Romanov
Andrew Romanov

Reputation: 5076

To solve this, you can use a Strides class and a map method:

let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]
let monthData = stride(from: 1, to: months.count, by: 2).map { (value:Int) -> String in
    return months[value]
}
print(monthData)

Upvotes: 0

Kilian Obermeier
Kilian Obermeier

Reputation: 7168

Swift 3 (based on @maxkonovalov's answer)

let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let step = 2
let filtered = array.enumerated().flatMap { $0.offset % step == 0 ? $0.element : nil }

// filtered: ["0", "2", "4", "6", "8"]

Upvotes: 2

maxkonovalov
maxkonovalov

Reputation: 3719

There's a more compact version to filter an array by element's index.

An example of how to find every Nth element in an array (swift 2.0):

let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let n = 2
let filteredArray =  array.enumerate().flatMap { $0.index % n == 0 ? $0.element : nil }

// filteredArray = ["0", "2", "4", "6", "8"]

Upvotes: 0

Anusha Kottiyal
Anusha Kottiyal

Reputation: 3905

You can also use the swift array filter method to get the filtered array,

monthData = months.filter{ (dataValue) in (find(months, dataValue)! % 2 != 0) }

Upvotes: 3

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

Try to use modulo operator ( % )

var monthData = Array<String>()
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"]

var i : Int = 1

for month in months{
    if(i%2 == 0){
        monthData.append(month)
    }
    i = i + 1
}

println(monthData)

Output :

[Aug 12, Oct 12]

Upvotes: 6

Related Questions