Zip And Partition Arrays

Combine parallel arrays into tuples and split a collection by predicate, with a zipLongest variant that pads short inputs.

JavascriptData Integrity

Code

javascriptsnippet
30 lines
export function zipArrays(...arrays) {
  if (arrays.length === 0) return [];
  const length = Math.min(...arrays.map((array) => array.length));
  const result = [];
  for (let index = 0; index < length; index += 1) {
    result.push(arrays.map((array) => array[index]));
  }
  return result;
}

export function zipLongest(fillValue = null, ...arrays) {
  const length = Math.max(0, ...arrays.map((array) => array.length));
  const result = [];
  for (let index = 0; index < length; index += 1) {
    result.push(arrays.map((array) => (index < array.length ? array[index] : fillValue)));
  }
  return result;
}

export function partitionArray(values, predicate) {
  if (!Array.isArray(values)) throw new TypeError("values must be an array");
  if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
  const truthy = [];
  const falsy = [];
  values.forEach((value, index) => {
    if (predicate(value, index, values)) truthy.push(value);
    else falsy.push(value);
  });
  return [truthy, falsy];
}

What the code does

Zip And Partition Arrays keeps everything in the functions zipArrays, zipLongest and partitionArray.

Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

The return value is newly constructed — inputs are never handed back.

Caveats

  • When its condition holds, the guard arrays.length === 0 breaks out of the current path via return.

Applying it

The primary signature is export function zipArrays(...arrays)

Callers only need zipArrays — everything else stays internal.

Statements that matter

if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
result.push(arrays.map((array) => (index < array.length ? array[index] : fillValue)));
if (!Array.isArray(values)) throw new TypeError("values must be an array");

Interactive Tools for This Topic

FAQ

Does `zipArrays` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What does the snippet do with malformed data?
Validation comes first — `TypeError` marks the failure at `arrays.length === 0`, before any partial work happens.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `zipArrays`, `zipLongest`, `partitionArray` at load time.