Problems › JavaScript › warmup
Break a list into fixed-size pieces
A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.
- Every piece is the given size except possibly the last, which takes what is left.
- A size of zero or less gives an empty result.
- An empty input gives an empty result, not a list holding one empty piece.
chunkList(values: list<int>, perChunk: int) → list<list<int>>
Where you start
function chunkList(values, perChunk) {
}
Worked examples
| Call | Result |
|---|---|
chunkList([1,2,3,4,5], 2) | [[1,2],[3,4],[5]] |
chunkList([1,2,3,4], 2) | [[1,2],[3,4]] |
chunkList([1], 5) | [[1]] |
chunkList([], 2) | [] |
Hint
Step the index forward by the chunk size and slice, rather than pushing one item at a time.
Reference solution in JavaScript
function chunkList(values, perChunk) {
if (perChunk <= 0) return [];
const result = [];
for (let i = 0; i < values.length; i += perChunk) result.push(values.slice(i, i + perChunk));
return result;
}