I have an array in Swift:
[1, 2, 3, 4, 5, 6, 7, 8]
I need to have X number of arrays each has n elements, say n = 3:
[1, 2, 3], [4, 5, 6], [7, 8]
So that if elements in the end are less than n the last sub-array will have whatever remaining.
I thought about using stride
:
let array = [1, 2, 3, 4, 5, 6, 7, 8]
let n = 3
var subarrays = [[Int]]()
for i in stride(from: 0, to: array.count, by: n) {
let slice = array[i..<min(i+n, array.count)]
subarrays.append(Array(slice))
}
I wonder if there's a better way of doing this?
Thanks!