TypeScript

zip — Pair Two Arrays

admin by @admin ADMIN
2m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Pair items from two arrays positionally into tuples. The result's length is the shorter of the two inputs. Useful for parallel arrays (labels + values, headers + rows).
TypeScript
Raw
export function zip<A, B>(a: readonly A[], b: readonly B[]): Array<[A, B]> {
  const len = Math.min(a.length, b.length);
  const out: [A, B][] = new Array(len);
  for (let i = 0; i < len; i++) out[i] = [a[i]!, b[i]!];
  return out;
}

zip(['x', 'y', 'z'], [1, 2, 3]);   // [['x',1], ['y',2], ['z',3]]

// Build a record from parallel arrays:
const headers = ['id', 'name', 'email'] as const;
const row = [42, 'Alice', 'a@x.com'];
const obj = Object.fromEntries(zip(headers, row));   // { id: 42, name: 'Alice', email: 'a@x.com' }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.