HOWTO · JavaScript

How to Zip Arrays in JavaScript

This article helps you to understand how to zip two or more arrays in JavaScript.

On this page

In JavaScript, there are situations when we wish to zip two arrays. We’ll examine flashing two collections with JavaScript in this tutorial.

The Python zip function’s JavaScript counterpart must be written. In other words, we need to make an array of pairs given many equal-length collections.

There are different ways in which we can zip two arrays in JavaScript, such as using the map() method, Array.from() method, and Array.prototype.fill() method.

Use the map Method to Zip Arrays in JavaScript

The map() function in JavaScript compresses two arrays of a certain length. However, it results in undefined if the length of both arrays does not match.

let a = [9, 8, 7];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
  return [e, b[i]];
});
console.log(zip);

Run Code

The call-back function that the map() method accepts will call the elements of the a array and the elements of the b array mapped with the a collection. It’s also straightforward to learn how to zip up in this manner.

Output:

[[9, "1"], [8, "2"], [7, "3"]]

While using the map method, ensure that the length of both arrays must be the same; otherwise, you will get the result undefined.

let a = [9, 8, 7, 6];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
  return [e, b[i]];
});
console.log(zip);

Demo Here

You can see that the lengths of the a and b arrays are different.

Output:

[[9, "1"], [8, "2"], [7, "3"], [6, undefined]]

Use the Array.from Method to Zip Arrays in JavaScript

let a = [9, 8, 7, 6];
let b = ['90', '80', '70', '60'];
let zip = (a, b) =>
    Array.from(Array(Math.max(a.length, b.length)), (_, i) => [a[i], b[i]]);
console.log(zip(a, b));

Run Code

Two arrays will be present in the instance of the Array.from method; they will be sent to an arrow function. After matching the length, the process will map the items from two separate arrays.

Output:

[[9, "90"], [8, "80"], [7, "70"], [6, "60"]]

Additionally, the equivalent map will output undefined for any missing element.

let a = [9, 8, 7];
let b = ['90', '80', '70', '60'];
let zip = (a, b) =>
    Array.from(Array(Math.max(a.length, b.length)), (_, i) => [a[i], b[i]]);
console.log(zip(a, b));

Demo Here

Output:

[[9, "90"], [8, "80"], [7, "70"], [undefined, "60"]]

The Array.prototype.fill() method works the same as Array.from() method.

let a = [7, 8, 9];
let b = ['70', '80', '90'];
let zip = (a, b) =>
    Array(Math.max(a.length, b.length)).fill().map((_, i) => [a[i], b[i]]);
console.log(zip(a, b));

Run Code

Output:

[[7, "70"], [8, "80"], [9, "90"]]