Home > Software design >  Swift 5 - Two Arrays together in one by selecting every nth from one
Swift 5 - Two Arrays together in one by selecting every nth from one

Time:05-19

actually i'm learning swift with Xcode 11.3.1 to build apps.

I got a question for working with arrays.

I have two arrays and want to combine both by selecting most of values from array one and every nth from array two. Example:

let arr1 = ["Value 1", "Value 2", "Value 3" "Value 4", "Value 5", "Value 6"]
let arr2 = ["Insert 1", "Insert 2", "Insert 3"]

Output should be: Value 1, Value 2, Insert 1, Value 3, Value 4, Insert 2 ...

If arr1 is ended append the last values from arr2 at the end and of course the other way around.

I can put the two arrays together and .shuffle() them but that's not what I finally want.

Hope someone can give a hint or a solution.

PS: In JS I know I can user methods like .reduce and push with using the modulator-operator but this is not JS ;-)

Kind regards, Steven

CodePudding user response:

I Gave it a try and able to genreate result as below : -

   Result Array = ["Value 1", "Value 2", "Insert 1", "Value 3", "Value 4", "Insert 2", "Value 5", "Value 6", "Insert 3"]

The Code I used is as following : -

    let arr1 = ["Value 1", "Value 2", "Value 3", "Value 4", "Value 5", "Value 6"]
    let arr2 = ["Insert 1", "Insert 2", "Insert 3"]
    var arrayResult : [String] = []
    let totallength = arr1.count   arr2.count
    var count = 0
    for i in 1...totallength {
        if i % 3 == 0 {
            arrayResult.append(arr2[count])
            count  = 1
        } else {
            arrayResult.append(arr1[i - count - 1])
        }
    }
    print("Result Array = \(arrayResult)")

Hope you found it useful.

CodePudding user response:

Reduce might be a good option. Just an example from swift, not optimal in performance, but I think it´s readable what it does.

arr2.reduce([]) { partialResult, value in
   partialResult.append(arr1.removeFirst(2))
   partialResult.append(value)
}
  • Related