zip
Zips two arrays into an array of pairs (tuples). Stops when the shortest array ends.
1/**
2 * Zips two arrays into an array of pairs (tuples).
3 * Stops when the shortest array ends.
4 *
5 * @param a - First array.
6 * @param b - Second array.
7 * @returns Array of [a[i], b[i]] pairs.
8 */
9export function zip<T, U>(a: T[], b: U[]): [T, U][] {
10 const length = Math.min(a.length, b.length);
11 return Array.from({ length }, (_, i) => [a[i], b[i]]);
12}
Tuple-based pairing
Returns each element as a
[T, U]
tuple, which preserves types and structure clearly, especially useful in strongly typed TypeScript environments.Stops at the shortest array
Prevents undefined values in the result by truncating the pairing to the shorter of the two arrays — this avoids runtime issues and ensures clean data.
Immutable and predictable
Does not mutate the input arrays and produces a new array each time, making it safe for functional programming use.
Simple and performant
Uses
Array.from
and minimal logic for iteration, keeping the function concise and efficient.
Tests | Examples
1test('zip - basic usage', () => {
2 expect(zip([1, 2], ['a', 'b'])).toEqual([
3 [1, 'a'],
4 [2, 'b'],
5 ]);
6});
7
8test('zip - different lengths', () => {
9 expect(zip([1, 2, 3], ['a'])).toEqual([[1, 'a']]);
10 expect(zip([1], ['a', 'b'])).toEqual([[1, 'a']]);
11});
12
13test('zip - one array empty', () => {
14 expect(zip([], [1, 2])).toEqual([]);
15 expect(zip([1, 2], [])).toEqual([]);
16});
17
18test('zip - both arrays empty', () => {
19 expect(zip([], [])).toEqual([]);
20});
Common Use Cases
Parallel iteration over arrays
When two related arrays (e.g., keys and values, questions and answers) need to be processed in tandem.
Combining metadata with data
Useful for pairing additional labels or annotations with a core dataset for display, export, or reporting.
Forming key-value pairs
Frequently used to convert two flat arrays into an object via further processing like
Object.fromEntries(zip(keys, values))
.Data alignment in visualizations
Aligns multiple data streams into a single array suitable for plotting, charting, or tabular display.
Simulating tuple structures
Especially in languages that lack native tuples, this provides a convenient structure for paired values.