How Lodash unzip Reconstructs Grouped Arrays

The Lodash _.unzip method is an array utility designed to reverse the operation of _.zip by taking an array of grouped elements and regrouping them back into their original constituent arrays. This article explains how _.unzip processes nested array indices, performs matrix transposition to rearrange data, and handles edge cases such as arrays with uneven lengths.

The Transposition Mechanism

At its core, _.unzip performs a 2D matrix transposition. It accepts a single two-dimensional array (an array containing nested arrays) and maps the element at index [row][column] to index [column][row] in the output structure.

When executed, _.unzip processes the input through the following steps:

  1. Calculates Output Dimensions: It scans the nested arrays to determine the maximum length among them. This maximum length defines how many arrays the output will contain.
  2. Iterates by Index: It iterates from index 0 up to the determined maximum length.
  3. Regroups Values: For each iteration index i, it extracts the element located at index i from each nested array and groups them into a new array.
  4. Returns the Reconstructed Collection: It outputs a new array containing these newly formed arrays.

Basic Reconstruction Example

Consider an array containing grouped data representing names, identifiers, and statuses:

const _ = require('lodash');

const zipped = [
  ['Alice', 101, true],
  ['Bob', 102, false],
  ['Charlie', 103, true]
];

const unzipped = _.unzip(zipped);

console.log(unzipped);
// Output:
// [
//   ['Alice', 'Bob', 'Charlie'],
//   [101, 102, 103],
//   [true, false, true]
// ]

In this example, the first elements ('Alice', 'Bob', 'Charlie') are combined into the first output array, the second elements (101, 102, 103) form the second array, and the third elements form the third array.

Handling Unequal Array Lengths

If the nested arrays within the input are not of equal length, _.unzip standardizes the output by filling missing slots with undefined. The total number of output arrays always matches the length of the longest inner array.

const irregularZipped = [
  ['a', 1],
  ['b', 2, 'extra'],
  ['c']
];

const result = _.unzip(irregularZipped);

console.log(result);
// Output:
// [
//   ['a', 'b', 'c'],
//   [1, 2, undefined],
//   [undefined, 'extra', undefined]
// ]

Because the second array contains three elements, the output produces three reconstructed arrays. For indices where an inner array has no value, undefined is inserted to maintain consistent positional alignment.

Relationship to _.zip

In Lodash, _.zip and _.unzip share the same underlying logic. While _.zip accepts multiple array arguments using rest parameters (_.zip(...arrays)), _.unzip accepts a single array containing those nested arrays. Consequently, _.unzip can reconstruct collections produced by _.zip, and passing an unzipped collection back into _.unzip returns it to its grouped state.