JavaScript Snippet

Zip Multiple Arrays

Difficulty: Medium

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.

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

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.