Drill

ProblemsJavaScript › warmup

Break a list into fixed-size pieces

mediumwarmupJavaScript

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

chunkList(values: list<int>, perChunk: int) → list<list<int>>

Solve it in the editor →

Where you start

function chunkList(values, perChunk) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More warmup problems in JavaScript