How to zip two arrays in JavaScript?

Sometimes, we want to zip two arrays in JavaScript.

In this article, we’ll look at how to zip two arrays in JavaScript.

How to zip two arrays in JavaScript?

To zip two arrays in JavaScript, we call the array map method.

For instance, we write

const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1, 2, 3], ["a", "b", "c"]));

to create the zip function that calls a.map with a callback that returns an array with the entry k in a and entry b[i] in b.

And then we call zip with 2 equal sized arrays to zip them together.

The returned array will have arrays that have the values in [1, 2, 3] and ["a", "b", "c"] at the same index.

Conclusion

To zip two arrays in JavaScript, we call the array map method.