Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

unzip

Separates an array of pairs (tuples) into two arrays.

TypeScript
Copied!
1/**
2 * Separates an array of pairs (tuples) into two arrays.
3 *
4 * @param arr - An array of 2-item tuples.
5 * @returns A tuple of two arrays: one with all first items, and one with all second items.
6 *
7 * @example
8 * unzip([[1, 'a'], [2, 'b']]) // => [[1, 2], ['a', 'b']]
9 */
10export function unzip<T, U>(arr: [T, U][]): [T[], U[]] {
11  return arr.reduce<[T[], U[]]>(
12    (acc, [a, b]) => {
13      acc[0].push(a);
14      acc[1].push(b);
15      return acc;
16    },
17    [[], []]
18  );
19}
  • Inverts the zip operation

    Allows clean separation of paired data into independent arrays, effectively reversing the effect of zip.

  • Type-safe and tuple-aware

    Maintains strong typing through TypeScript generics, ensuring both output arrays have correct types: [T[], U[]].

  • Efficient single-pass processing

    Uses Array.prototype.reduce to build both result arrays in a single iteration, avoiding extra allocations or iterations.

  • Immutability

    Returns new arrays without mutating the original, supporting functional programming and predictable state handling.

  • Intuitive and minimal implementation

    Easy to understand and adapt for variations like triple tuples or n-tuples with a small extension.

Tests | Examples

TypeScript
Copied!
1test('unzip - separates tuple array correctly', () => {
2  expect(unzip([[1, 'a'], [2, 'b'], [3, 'c']])).toEqual([
3    [1, 2, 3],
4    ['a', 'b', 'c']
5  ]);
6});
7
8test('unzip - empty input', () => {
9  expect(unzip([])).toEqual([[], []]);
10});
11
12test('unzip - works with mixed types', () => {
13  const data: [number, { id: string }][] = [
14    [1, { id: 'x' }],
15    [2, { id: 'y' }]
16  ];
17  expect(unzip(data)).toEqual([
18    [1, 2],
19    [{ id: 'x' }, { id: 'y' }]
20  ]);
21});

Common Use Cases

  • Data restructuring

    Useful for transforming a list of entries like [[id, value], ...] into separate ID and value arrays for batch operations.

  • Splitting mapped results

    When a .map() operation returns tuples (e.g., [index, value]), unzip can help restore structure for separate handling.

  • Form or spreadsheet parsing

    Separates field/value or key/value pairs into rows and columns or distinct data tracks.

  • Graph or edge processing

    In algorithms working with pairwise data (like [from, to] edges), helps isolate nodes into separate start/end arrays.

  • Presentation formatting

    Supports rendering grouped data in UI components like tables or grids by isolating header/content tuples into separate sources.

Codebase: Utilities -> Arrays -> unzip | Yevhen Klymentiev