2

I have a multidimensional array called 'data' that is initialised as so:

var data = [[String]]()

I can add all of my required arrays to this without issue.

The problem I am facing is that I need all of the included arrays to have the same number of values (I am creating a spreadsheet and I need to have the same number of 'columns' in each array). To do this I am trying to:

  1. Find the count of the longest array
  2. Append a number of "" (i.e. blank values) to the end of each array to equal the max count

I am having zero success finding out how to do either of these things. Any advice?

2
  • Looks like you are trying to use a matrix like structure. see this link Commented Mar 16, 2018 at 15:22
  • Thanks for that. Will look into that. Not come across that before. Commented Mar 16, 2018 at 15:39

1 Answer 1

1

You can use a max function over data to get the number of elements of the longest array.

And then you can iterate over each element of the array and append "" until it reaches the desired size.

Here you have an example:

var data = [[String]]()

data = [["aaa", "bbb"], ["aaa", "bbb", "ccc"], ["aaa"]]

var longestArrayCount = data.max { $0.count < $1.count }?.count ?? 0

for (index, _) in data.enumerated() {
    data[index].append(contentsOf: Array(repeating: "", count: longestArrayCount - data[index].count))
}

print(data)

Output: [["aaa", "bbb", ""], ["aaa", "bbb", "ccc"], ["aaa", "", ""]]


Update

Applied change suggested by @BallpointBen

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

3 Comments

It would be be more efficient to do data[index].append(contentsOf: Array(repeating: "", count: longestArrayCount - data[index].count))
I totally agree :)
Works perfectly. Thank you both! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.