6

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"]

5 Answers 5

6

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]

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

2

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"]

Comments

0

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"]

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.