Divide array in chunks with different sizes

457 views Asked by At

I'm getting an array of data from HTML Scraping similar to this:

var resultArray = ["Maths", 2, 7, 8, "Grammar", 1, "Science", 7, 8]

What I want to do is do divide it when it finds a "String" value. The result should look like this:

var new_arr1 = ["Maths", 2, 7, 8]
var new_arr2 = ["Grammar", 1]
var new_arr2 = ["Science", 7, 8]

The problem is that if I use something like this:

func chunk(_ chunkSize: Int) -> [[Element]] {
    return stride(from: 0, to: self.count, by: chunkSize).map({ (startIndex) -> [Element] in
        let endIndex = (startIndex.advanced(by: chunkSize) > self.count) ? self.count-startIndex : chunkSize
        return Array(self[startIndex..<startIndex.advanced(by: endIndex)])
    })
}

I can only have a fixed "newArray" size.

Using Xcode8 and Swift3. Thanks in advance.

1

There are 1 answers

1
matt On

I think your entire spec is silly. You certainly cannot end up with a series of variables, as you propose. And to end up with yet another mixed array of string and numbers is completely counterproductive. You should rethink your goals (and if possible, you should rewrite your scraping code so as not to end up with a mixed array in the first place).

Anyway, given the input, here's how to end up with an array of tuples:

let resultArray : [Any] = ["Maths", 2, 7, 8, "Grammar", 1, "Science", 7, 8]
let nums = resultArray.split{$0 is String}
let strings = resultArray.filter{$0 is String}
let result = Array(zip(strings, nums)).map{($0, Array($1))}
print(result) // [("Maths", [2, 7, 8]), ("Grammar", [1]), ("Science", [7, 8])]