Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

Cut elements of array in Swift 2

I have array of elements (it's a basic array). Type of array is String

basicArray = [1710, 1725, 1740, 1755, 1810, 1825, 1840, 1855, 1925, 1955, 2020, 2050, 2120, 2150, 2220, 2250, 2320, 2350, 2430]

I need to create two new arrays where each element of basicArray must be cut into two parts, for example:

array1 = [17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20....]
array2 = [10, 25, 40, 55, 10, 25, 40, 55, 25,55, 20, 50...]

How better to do it? Thank you for your advice!

Upvotes: 2

Views: 176

Answers (3)

the_critic
the_critic

Reputation: 12820

Swift has a built in method called filter which basically is a closure that iterates over all elements and lets you -- as the name suggests -- filter the elements based on a predicate:

let array = [1,2,3,4,5,6]

let array1 = array.filter { $0 % 2 == 0 }
print(array1) // [2, 4, 6]
let array2 = array.filter { $0 % 2 == 1 }
print(array2) // [1,3,5]

You haven't made clear how you want those arrays to be filtered, so it's hard to explicitly give the answer that you might be looking for...

Upvotes: -2

ronatory
ronatory

Reputation: 7324

Try this (Hints are in the code comments):

var basicArray = [1710, 1725, 1740, 1755, 1810, 1825, 1840, 1855, 1925, 1955, 2020, 2050, 2120, 2150, 2220, 2250, 2320, 2350, 2430]
var firstTwoDigitsArray = [Int]()
var lastTwoDigitsArray = [Int]()

for element in basicArray {

    // dividing by 100 shifts the numbers down by the first two digits
    firstTwoDigitsArray.append(element/100)

    // modulo 100 gets the last two digits 
    lastTwoDigitsArray.append(element%100)

}

print(firstTwoDigitsArray) // [17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24]
print(lastTwoDigitsArray) // [10, 25, 40, 55, 10, 25, 40, 55, 25, 55, 20, 50, 20, 50, 20, 50, 20, 50, 30]

Upvotes: 0

Eendje
Eendje

Reputation: 8883

let basic = ["1710", "1725", "1740", "1755", "1810", "1825", "1840", "1855", "1925", "1955", "2020", "2050", "2120", "2150", "2220", "2250", "2320", "2350", "2430"]
let array1 = basic.map { String($0.characters.prefix(2)) }
let array2 = basic.map { String($0.characters.suffix(2)) }

print(array1)
print(array2)

Output:

["17", "17", "17", "17", "18", "18", "18", "18", "19", "19", "20", "20", "21", "21", "22", "22", "23", "23", "24"]
["10", "25", "40", "55", "10", "25", "40", "55", "25", "55", "20", "50", "20", "50", "20", "50", "20", "50", "30"]

Something like this?

Upvotes: 9

Related Questions