How Lodash _.unzip Handles Asymmetrical Arrays

When working with the Lodash JavaScript library, the _.unzip method reverses the grouping of nested arrays by reorganizing elements based on their shared indices. When sub-arrays have asymmetrical or unequal lengths, _.unzip determines the output dimensions using the longest array present, automatically inserting undefined for any missing values. This article explains the internal mechanics, demonstrates typical output through examples, and highlights key considerations for working with uneven datasets.

The Core Mechanism of _.unzip

The _.unzip function accepts an array of arrays and produces a new two-dimensional array. Rather than truncating data to match the shortest nested array, Lodash prioritizes data preservation by targeting the sub-array with the maximum length.

  1. Calculates Maximum Length: The function scans the provided nested arrays to identify the largest length property. The resulting outer array will have a length equal to this maximum value.
  2. Sequential Regrouping: An iteration runs from index 0 up to maxLength - 1. For each index, _.unzip collects the element at that index from each inner array.
  3. Sparse Padding: If an inner array does not contain an element at the current index (because its length is shorter), JavaScript's default lookup returns undefined. Lodash assigns this undefined value directly into the corresponding position of the new sub-array.

Practical Code Demonstration

Consider an input array containing three nested arrays of varying lengths: four items, two items, and one item.

const _ = require('lodash');

const asymmetricalData = [
  ['a', 'b', 'c', 'd'],
  [1, 2],
  [true]
];

const result = _.unzip(asymmetricalData);

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

Because the first array has four elements, the returned array contains four sub-arrays. The values from shorter arrays are extracted where available, while non-existent positions are filled with undefined.

Working with Holes and Sparse Arrays

Lodash treats absent indices in sparse arrays similarly to out-of-bounds indices in short arrays. If an inner array has missing indices (e.g., [1, , 3]), _.unzip will map that empty slot to undefined. This guarantees that the dimensionality of the generated output remains predictable and symmetrical, regardless of how irregular the input matrices are.

Handling the Resulting undefined Values

When processing the unzipped results, operations that do not expect undefined values can encounter errors or produce unexpected logic branches. Developers commonly address these padded values using standard patterns: