What Data Structure Does Lodash zip Create?

This article examines the data structure produced when grouping multiple arrays using the _.zip method in the Lodash JavaScript library. It details how the method transforms input elements into a unified structure, handles mismatched array lengths, and functions within real-world JavaScript data processing workflows.

The Resulting Data Structure: A Two-Dimensional Array

When you pass multiple arrays into Lodash's _.zip function, the returned data structure is a two-dimensional array (also referred to as a nested array or an array of arrays).

Specifically, _.zip creates a new outer array containing multiple inner arrays. Each inner array groups together the elements that share the same index across all provided input arrays. The first inner array contains the first elements of every input array, the second inner array contains the second elements, and this pattern continues sequentially.

Basic Code Example

const _ = require('lodash');

const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
const active = [true, false, true];

const zipped = _.zip(names, ages, active);
console.log(zipped);

Output:

[
  ['Alice', 25, true],
  ['Bob', 30, false],
  ['Charlie', 35, true]
]

In TypeScript notation, if all input arrays are of the same type T, the resulting type is T[][]. If the input arrays contain different types, the resulting type is an array of tuples containing those respective types.

Matrix Transposition Behavior

In mathematical and computer science terms, _.zip performs a matrix transposition. If you view the input arguments as rows of a matrix:

The resulting structure transposes these rows into columns:

Handling Arrays of Unequal Length

When the input arrays are not of equal length, _.zip determines the length of the outer array by the longest input array. For any shorter arrays that lack an element at a given index, Lodash populates that position with undefined.

const keys = ['id', 'status', 'role', 'extra'];
const values = [101, 'active', 'admin'];

const result = _.zip(keys, values);

Output:

[
  ['id', 101],
  ['status', 'active'],
  ['role', 'admin'],
  ['extra', undefined]
]

The resulting structure remains a two-dimensional array, maintaining index alignment across all categories even when data is missing.