Code Snippets
/

Zip Multiple Arrays

Zip Multiple Arrays

Python users miss `zip(a, b)` and the Lodash crowd reaches for `_.zip`, but JavaScript can do this cleanly with one helper. This snippet covers the basic two-array zip, an N-array variadic version, the unzip inverse, and a `zipWith` that lets you fold pairs into custom shapes (records, objects, weighted sums). It also clarifies the truncate-to-shortest vs. fill-with-undefined trade-off.

JavaScript
Medium
4 snippets
arrays
utility
array-manipulation-patterns
functional-programming

1,003 views

6

function zip2(a, b) {
    const len = Math.min(a.length, b.length);
    const out = new Array(len);
    for (let i = 0; i < len; i++) {
        out[i] = [a[i], b[i]];
    }
    return out;
}

const names = ['Ada', 'Bo', 'Cal'];
const ages = [30, 25, 40];

console.log(zip2(names, ages));
// [['Ada', 30], ['Bo', 25], ['Cal', 40]]

// Truncate-to-shortest is the safe default.
console.log(zip2(['a', 'b', 'c', 'd'], [1, 2]));
// [['a', 1], ['b', 2]]

The simplest zip walks both arrays in lockstep and emits [a[i], b[i]] pairs until the shorter input runs out. Pre-allocating with new Array(len) skips the array growth dance V8 does when you push repeatedly, which matters on hot paths. Truncating to the shortest length is the safer default: if a downstream map callback expects a defined element from each side, padding with undefined would only push the bug one step away. The whole pass is O(n) time and O(n) output.

Zip Multiple Arrays | Code Snippets | CodeSnatch