← Back to JavaScript, page 6

javascript-0103 · Easy fresher

How do you write chunk, zip, unzip, and range helper functions for arrays?

Chunk uses a loop with slice and a step, zip uses Array.from with the shortest length and index access, unzip is zip applied to the rows, and range uses Array.from with a length formula. Handle empty input, a size of zero or less, and uneven lengths on purpose.

Full answer

These four helpers appear in almost every coding screen, and each one is short when you know the right built-ins.

chunk(array, size) splits an array into groups. Loop with i += size and push array.slice(i, i + size). The last group can be shorter. Reject sizes below 1, otherwise the loop never ends. The result for an empty array is an empty array.

zip(a, b, ...) pairs items by index: zip([1, 2], ['a', 'b']) gives [[1, 'a'], [2, 'b']]. Decide what to do when lengths differ. The common choice is the shortest length (Python behaviour). The alternative is the longest length, filling with undefined. Build it with Array.from({ length }, (_, i) => arrays.map((array) => array[i])).

unzip reverses zip. It is the same function applied to the pairs: zip(...pairs). That works because transposing a matrix twice gives the original.

range(start, end, step) produces numbers. Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step) is clear and avoids the floating point drift of repeated addition. Support a single argument as the end, a negative step, and a step of zero as an error.

Details that interviewers check: the original arrays must not change, empty input must work, and the code must not use new Array(n) with map, because that array has holes that map skips.

javascript
function chunk(array, size) {
  if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
  const groups = [];
  for (let i = 0; i < array.length; i += size) groups.push(array.slice(i, i + size));
  return groups;
}

function zip(...arrays) {
  if (arrays.length === 0) return [];
  const length = Math.min(...arrays.map((array) => array.length));
  return Array.from({ length }, (_, i) => arrays.map((array) => array[i]));
}

const unzip = (pairs) => (pairs.length === 0 ? [] : zip(...pairs));

function range(start, end, step = 1) {
  if (end === undefined) [start, end] = [0, start];
  if (step === 0) throw new RangeError('step must not be 0');
  const length = Math.max(0, Math.ceil((end - start) / step));
  return Array.from({ length }, (_, i) => start + i * step);
}

console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(chunk([], 3), chunk([1, 2], 5));
try {
  chunk([1], 0);
} catch (error) {
  console.log('chunk size 0:', error.name);
}
console.log(zip([1, 2, 3], ['a', 'b']));
const pairs = zip([1, 2], ['x', 'y']);
console.log(pairs, unzip(pairs));
console.log(range(4), range(2, 6), range(10, 0, -3), range(0, 1, 0.25));
console.log(range(3, 3), zip(), new Array(3).map((_, i) => i));

Run with Node.js v24.22.1 as js-103.js; two runs gave identical output. Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] [] [ [ 1, 2 ] ] chunk size 0: RangeError [ [ 1, 'a' ], [ 2, 'b' ] ] [ [ 1, 'x' ], [ 2, 'y' ] ] [ [ 1, 2 ], [ 'x', 'y' ] ] [ 0, 1, 2, 3 ] [ 2, 3, 4, 5 ] [ 10, 7, 4, 1 ] [ 0, 0.25, 0.5, 0.75 ] [] [] [ <3 empty items> ]

Key points

  • chunk: loop in steps of size with slice; reject size below 1.
  • zip: build by index with Array.from; choose shortest or longest length on purpose.
  • unzip is zip applied to the pairs.
  • range: Array.from with a length formula; handle negative steps and reject a zero step.
  • Do not mutate the input and avoid holey arrays from new Array(n).

Common mistakes

  • Forgetting to reject a chunk size of 0, which makes an endless loop.
  • Building ranges with repeated floating point addition and getting drift.
  • Using new Array(n).map to create sequences.
  • Mutating the input arrays with splice.

Follow-ups

  • How would you make zip use the longest length and fill missing values?
  • How would you write range as a lazy generator?
  • How would you chunk by total string length instead of by item count?

Tips

  • Ask what to do with uneven lengths and bad sizes before coding.
  • Prefer Array.from with a length object for sequences.
  • Show one test for empty input.