javascript 20 lines · 6 steps

Three ways to zip arrays in JavaScript

A small toolkit that pairs two arrays into tuples, an object, or a padded set of pairs.

Explained by highlit
1function zip(keys, values) {
2 if (keys.length !== values.length) {
3 throw new RangeError('zip expects arrays of equal length');
4 }
5 return keys.map((key, index) => [key, values[index]]);
6}
7 
8function zipToObject(keys, values) {
9 return Object.fromEntries(zip(keys, values));
10}
11 
12function zipLongest(keys, values, fill = null) {
13 const length = Math.max(keys.length, values.length);
14 return Array.from({ length }, (_, index) => [
15 index < keys.length ? keys[index] : fill,
16 index < values.length ? values[index] : fill,
17 ]);
18}
19 
20export { zip, zipToObject, zipLongest };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Pairing arrays by index is just a map over one array reaching into the other.
  2. 2Object.fromEntries turns a list of key-value pairs directly into an object.
  3. 3Choosing to throw versus pad with a fill value is how you handle mismatched lengths.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Three ways to zip arrays in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code