Create chunks from an array
05AB1E, 1 byte
ô
Try it online or verify all test cases.
Builtins ftw. :)
JavaScript (ES6), 36 bytes
Takes input as (n)(array)
.
n=>g=a=>a+a&&[a.splice(0,n),...g(a)]
Try it online!
Commented
n => // n = chunk size
g = a => // g = recursive function taking the array a[]
a + a // if a[] is empty, stop recursion and return an empty string
&& // otherwise, return an array made of:
[ a.splice(0, n), // the next chunk
...g(a) // followed by the result of a recursive call
] // (the last call leads to ...'', which adds nothing)
APL (Dyalog Unicode), 12 bytesSBCS
⊢⊂⍨(⍴⊢)⍴1↑⍨⊣
Big thanks to Adám for basically doing basically all the golfing (and for basically all the APL knowledge I have currently >_>).
Explanation
⊂⍨ Partitioned enclose (commuted, i.e. left and right switched) - for each ⍵ in left, ⍺ in right, if ⍺ = 0, create a new sub-array, push ⍵ to latest sub-array
⊢ Right argument of entire expression
⍴ Reshape - Change size of right into dimensions specified by left
(⍴ ) Shape of (here, there is only one dimension - length)
⊢ Right argument of entire expression
↑⍨ Take (commuted) - takes ⍺ elements from left where ⍺ is right. Extra elements (zeroes here) are automatically added
1 1
⊣ Left argument of entire expression
Execution
Arguments 2
, 1 2 3 4 5 6 7
. Note that APL arrays are of the form a b c
, with optional surrounding parentheses.
⊣ 2
1 1
↑⍨ 1↑2 = 1 0
⊢ 1 2 3 4 5 6 7
(⍴ ) ⍴1 2 3 4 5 6 7 = 7
⍴ 7⍴1 0 = 1 0 1 0 1 0 1
⊢ 1 2 3 4 5 6 7
⊂⍨ 1 0 1 0 1 0 1⊂1 2 3 4 5 6 7 = (1 2)(3 4)(5 6)(7)
Try it online!