Given an array of any kind and the wanted number of subarray, i need this output :
print([0, 1, 2, 3, 4, 5, 6].splitInSubArrays(into: 3))
// [[0, 3, 6], [1, 4], [2, 5]]
Output must contain the correct number of subarrays even if there is not "enough" elements to fill those :
print([0, 1, 2].splitInSubArrays(into: 4))
// [[0], [1], [2], []]
I have this working implementation for now but is there a better (more elegant) way of achieving this output :
extension Array {
func splitInSubArrays(into size: Int) -> [[Element]] {
var output: [[Element]] = []
(0..<size).forEach {
var subArray: [Element] = []
for elem in stride(from: $0, to: count, by: size) {
subArray.append(self[elem])
}
output.append(subArray)
}
return output
}
}