Drill

ProblemsTypeScript › warmup

Break a list into fixed-size pieces

mediumwarmupTypeScript

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: number[], perChunk: number): number[][] {
  
}

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 TypeScript
function chunkList(values: number[], perChunk: number): number[][] {
  if (perChunk <= 0) return [];
  const result: number[][] = [];
  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 TypeScript