Emmanuel Akinfulubi

JavaScriptArray

Zip two arrays together in JavaScript

Intermediate · 4 min read

To zip two lists means to pair them up by position, like the two sides of a zip fastener. The first item of one list goes with the first item of the other, the second with the second, and so on. You do this when you have column names in one list and values in another, or dates in one list and prices in another.

In this tutorial you will write zip, which pairs up two lists, and unzip, which takes the pairs apart again. You will also decide what should happen when the lists are different lengths, because JavaScript has no built-in zip to decide for you. You should know arrays, map and arrow functions.

Building an array from a length

Array.from({ length: n }, fn) makes a new array with n items. For each index i, it calls fn and stores the result.

JavaScript

console.log(Array.from({ length: 3 }, (_, i) => i * 10)); // [ 0, 10, 20 ]

The callback gets two arguments: a value, which is always undefined here, and the index. We only want the index, so the first argument is named _, a common way to say "not used".

This is handy for zipping. You decide how long the result should be, then read the same index from both lists.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

22 Zip two lists together

fair

Pair up two lists by position, then take a list of pairs apart again. Decide what happens when the lists are different lengths, and write both answers.

Stuck? Three hints, smallest first
  1. 1. Build the result from the length you decide on, then index both inputs.
  2. 2. Math.min truncates to the shorter list; Math.max plus a pad value keeps everything.
  3. 3. Object.fromEntries turns a list of pairs straight into an object.

Step 1: pair two lists of the same length

Step 1

const zip = (as, bs) =>
  Array.from({ length: Math.min(as.length, bs.length) }, (_, i) => [as[i], bs[i]]);
console.log(zip([1, 2], ['a', 'b'])); // [ [ 1, 'a' ], [ 2, 'b' ] ]

Each pair is a small array of two items: [as[i], bs[i]]. For lists of equal length, the length of the result is just that length.

Step 2: lists of different lengths

What if one list is longer? Math.min picks the smaller length, so the extra items are left out.

Step 2

const zip = (as, bs) =>
  Array.from({ length: Math.min(as.length, bs.length) }, (_, i) => [as[i], bs[i]]);
console.log(zip([1, 2, 3], ['a'])); // [ [ 1, 'a' ] ]
console.log(zip([1, 2], []));       // []

This is called truncating: cutting off at the shorter list. It is a sensible choice when a pair with a missing half is useless, like a column name with no value.

Step 3: the other choice, padding

Sometimes you can't afford to lose items. Then use the longer length and fill the gaps with a stand-in value, here null.

Step 3

const zipPad = (as, bs, pad = null) =>
  Array.from({ length: Math.max(as.length, bs.length) }, (_, i) => [
    i < as.length ? as[i] : pad,
    i < bs.length ? bs[i] : pad,
  ]);
console.log(zipPad([1, 2, 3], ['a'])); // [ [ 1, 'a' ], [ 2, null ], [ 3, null ] ]

pad = null is a default parameter: if the caller doesn't pass a third argument, pad is null. The check i < as.length asks "does this list still have an item here?" before reading it.

Both answers are reasonable, which is exactly why there is no built-in zip. Pick one and say so in the name, as zipPad does.

Step 4: unzip

unzip goes the other way. Given a list of pairs, collect every first item into one list and every second item into another.

Step 4

const zip = (as, bs) =>
  Array.from({ length: Math.min(as.length, bs.length) }, (_, i) => [as[i], bs[i]]);
const unzip = (pairs) => [pairs.map((p) => p[0]), pairs.map((p) => p[1])];
console.log(unzip([[1, 'a'], [2, 'b']]));      // [ [ 1, 2 ], [ 'a', 'b' ] ]
console.log(unzip(zip([1, 2], ['a', 'b']))); // [ [ 1, 2 ], [ 'a', 'b' ] ]

The second line zips two lists and unzips the result, and you get the two lists back. That round trip is a quick way to convince yourself both functions are right.

Step 5: pairs into an object

Here is the practical payoff. Object.fromEntries takes a list of [key, value] pairs and builds an object from them. A zipped list is exactly that shape.

Step 5

const zip = (as, bs) =>
  Array.from({ length: Math.min(as.length, bs.length) }, (_, i) => [as[i], bs[i]]);
const keys = ['route', 'price'];
const values = ['Yaba', 450];
console.log(Object.fromEntries(zip(keys, values))); // { route: 'Yaba', price: 450 }
console.log(Array.isArray(zip([1], ['a'])[0]));    // true

A header row and a data row become one record in a single line. That is most of what reading a CSV file comes down to. The last line is a reminder that a zipped pair is still an array, not an object, until you pass it to Object.fromEntries.

The full solution

The panel has zip, zipPad and unzip, then runs them on even lists, uneven lists and a header row. Press Run and compare the truncated and padded results.

The answer

const zip = (as, bs) =>
  Array.from({ length: Math.min(as.length, bs.length) }, (_, i) => [as[i], bs[i]]);

// The other reasonable answer: keep every element and pad the gaps.
const zipPad = (as, bs, pad = null) =>
  Array.from({ length: Math.max(as.length, bs.length) }, (_, i) => [
    i < as.length ? as[i] : pad,
    i < bs.length ? bs[i] : pad,
  ]);

const unzip = (pairs) => [pairs.map((p) => p[0]), pairs.map((p) => p[1])];

const keys = ['route', 'price'];
const values = ['Yaba', 450];

console.log('zip        :', zip([1, 2], ['a', 'b']));
console.log('uneven     :', zip([1, 2, 3], ['a']), '<- truncated to the shorter one');
console.log('padded     :', zipPad([1, 2, 3], ['a']));
console.log('unzip      :', unzip([[1, 'a'], [2, 'b']]));
console.log('as an object:', Object.fromEntries(zip(keys, values)));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('zip pairs by position', zip([1, 2], ['a', 'b']), [[1, 'a'], [2, 'b']]);
test('the shorter list decides the length', zip([1, 2, 3], ['a']), [[1, 'a']]);
test('zipping with an empty list gives nothing', zip([1, 2], []), []);
test('the padding version keeps every element', zipPad([1, 2, 3], ['a']).length, 3);
test('and marks the gaps', zipPad([1, 2, 3], ['a'])[1], [2, null]);
test('unzip is the inverse of zip', unzip([[1, 'a'], [2, 'b']]), [[1, 2], ['a', 'b']]);
test('so zip then unzip round-trips', unzip(zip([1, 2], ['a', 'b'])), [[1, 2], ['a', 'b']]);
test('pairs convert straight into an object', Object.fromEntries(zip(keys, values)), { route: 'Yaba', price: 450 });
test('and a zipped pair is an array, not an object', Array.isArray(zip([1], ['a'])[0]), true);

There is no built-in zip, and the reason is the disagreement this exercise makes explicit: with lists of different lengths, truncating and padding are both defensible, so the language leaves the choice to you. Say which one you picked in the function's name.

zip plus Object.fromEntries is the practical payoff — a header row and a data row become a record in one line, which is most of what reading a CSV amounts to.

Common mistakes

  • Using the first list's length without thinking. If the second list is shorter, you get pairs like [3, undefined] without having chosen that. Pick Math.min or Math.max on purpose.
  • Forgetting null and undefined look alike. In zipPad, a real null in the data looks the same as a gap. Choose a pad value that can't appear in your data if that matters.
  • Expecting unzip to restore what truncation removed. Items cut off by zip are gone. Unzipping only gives back what was paired.

Try it yourself

  1. Zip ['Mon', 'Tue', 'Wed'] with [21, 23, 22] and print each pair as 'Mon: 21'.
  2. Write zip3(as, bs, cs) that makes triples instead of pairs.
  3. Turn the object { route: 'Yaba', price: 450 } back into two lists, keys and values. (Hint: Object.entries and your unzip.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.