0

I have an array of Strings, and I would like to group the content by three to create arrays within the array.

For instance:

var arrayOfStrings = ["a0", "a1", a2", "b0", "b1", "b2"]

And I am looking to achieve:

var multiDimensionalArray = [["a0", "a1", a2"], ["b0", "b1", "b2"]]

Therefore, I am looking for a function that could group the elements within arrayOfStrings in arrays containing 3 elements, in the right order.

Thank you,

3 Answers 3

1

Try this function:

func makeMultidimensional(a: [String]) -> [[String]] {
    var result: [[String]] = []
    for var i = 0; i < a.count; i += 3 {
        result.append([a[i], a[i + 1], a[i + 2]])
    }
    return result
}

print(makeMultidimensional(arrayOfStrings)) // prints [["a0", "a1", "a2"], ["b0", "b1", "b2"]]

It iterates over array of strings and adds new array of 3 items to the result every time.

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

Comments

0

very simple

NSArray *multiDimensionalArray = @[@[@"a0", @"a1", @"a2"], @[@"b0", @"b1", @"b2"]];

for swift

var multiDimensionalArray = [["a0", "a1", "a2"], ["b0", "b1", "b2"]];

runnig on my system well

3 Comments

I think OP is looking for solutions in Swift
Well Bhai Jagveer OP want a solution. He knows how to declare multiDimensionalArray (as you did) , look in his question.
great thanks, actualy i dont understand the quetion!!
0
func makeMultidimensional<T>(input:[T], dimensions:Int) -> [[T]]?
{
    if dimensions <= 0 || count(input) % dimensions > 0 {
        return nil
    }

    return
        input.reduce(([[T]](), [T]())) {
            if 0..<dimensions-1 ~= count($0.1) {
                return ($0.0, $0.1 + [$1])
            }
            else {
                return ($0.0 + [$0.1 + [$1]], [])
            }
        }.0
}

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.