Extension method to split array into multiple chunks?
Posted: 21 Aug 2020, 03:18
is there a better way than https://www.autohotkey.com/boards/viewtopic.php?t=65635? looks way too complicated from here, i would like to have something like array_of_chunks := array.chunks(max_items_per_chunk)
I tried making the method myself but it didn't have much success :c
returned
Code: Select all
array := [1,2,3,4,5]
chunks := array.chunks(2)
; chunks is [[1,2],[3,4],[5]]
for i, chunk in chunks {
; do something with the chunk
}
Code: Select all
chunks(max) {
if (this.Count() =< max)
return [this]
arrays := [[]]
chunk := 1
_i := 1
for i, item in this {
_i++
if (_i > max) {
_i := 0
chunk++
arrays[chunk] := []
}
arrays[chunk].push(item)
}
return arrays
}
Code: Select all
txt := [ toJson([1,2,3,4,5].chunks(0))
,toJson([1,2,3,4,5].chunks(1))
,toJson([1,2,3,4,5].chunks(2))
,toJson([1,2,3,4,5].chunks(3))
,toJson([1,2,3,4,5].chunks(4))
,toJson([1,2,3,4,5].chunks(5))
,toJson([1,2,3,4,5].chunks(6))]
MsgBox % "`n".join(txt)
Code: Select all
---------------------------
temp-2020-08-21-10-52-53.ahk
---------------------------
[{},[1],[2],[3],[4],[5]]
[{},[1,2],[3,4],[5]]
[[1],[2,3,4],[5]]
[[1,2],[3,4,5]]
[[1,2,3],[4,5]]
[[1,2,3,4],[5]]
[[1,2,3,4,5]]
---------------------------
OK
---------------------------