1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How To Zip Two Or More Arrays In JavaScript - A Comprehensive Guide

ReadTime: 6 minutes

In JavaScript, zipping two or more arrays refers to the process of combining their elements into pairs. This guide will take you through various methods to achieve this.


What is Zip?

In programming, zipping arrays involves merging corresponding elements from multiple arrays into pairs. For example, given two arrays:

javascript
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

// Zipped array: [[1, 'a'], [2, 'b'], [3, 'c']]
console.log(zipArrays(array1, array2));
Zipping arrays example

How to Zip Two Arrays in JavaScript

Method 1: Using a Loop

The zipArrays function iterates through the arrays and combines corresponding elements into pairs, creating a new array.

javascript
function zipArrays(arr1, arr2) {
const zipped = [];
for (let i = 0; i < Math.min(arr1.length, arr2.length); i++) {
  zipped.push([arr1[i], arr2[i]]);
}
return zipped;
}

const array1 = [1, 2, 3];
const result = zipArrays(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Using a loop to zip arrays

Note: We only zipped till length of the shorter array, because we can only form pair till then.

Method 2: Using the Map Function

We can use the map function to create a new array by pairing corresponding elements from the input arrays.

javascript
function zipArrays(arr1, arr2) {
return arr1.map((element, index) => [element, arr2[index]]);
}

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const result = zipArrays(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Using map function to zip arrays

Method 3: Zip Two Arrays using the reduce() Method

This method utilizes the reduce method to accumulate the zipped array by iteratively combining corresponding elements.

javascript
function zipWithReduce(...arrays) {
  const length = Math.min(...arrays.map(arr => arr.length));
  return arrays.reduce((zipped, _, index) => {
      for (let i = 0; i < length; i++) {
        zipped[i].push(arrays[index][i]);
      }
      return zipped;
  }, Array.from({ length }, () => []));
}

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

const result = zipWithReduce(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Using reduce() to zip arrays

Method 4: Zip Two Arrays using the forEach() Method

The forEach method is employed to iterate through arrays, combining corresponding elements and forming the zipped array.

javascript
function zipWithForEach(...arrays) {
  const length = Math.min(...arrays.map(arr => arr.length));
  const zipped = Array.from({ length }, () => []);

  arrays.forEach((arr, index) => {
      for (let i = 0; i < length; i++) {
          zipped[i].push(arr[i]);
      }
  });

  return zipped;
}

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

const result = zipWithForEach(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Using forEach() to zip arrays

Defining a Reusable zip() Function

The zip function accommodates any number of arrays, creating pairs by iterating over the elements at each index.

javascript
function zip(...arrays) {
  const length = Math.min(...arrays.map(arr => arr.length));
  return Array.from({ length }, (_, index) => arrays.map(arr => arr[index]));
}

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const result = zip(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]
Reusable zip function

Zip Two Arrays of Different Lengths

When zipping arrays of different lengths, the resulting array will have a length equal to the shorter array.

javascript
const array1 = [1, 2, 3];
const array2 = ['a', 'b'];
const result = zipArrays(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b']]
Zipping arrays of different lengths

Zip Multiple Arrays in JavaScript

The zip function can handle any number of arrays, creating pairs for each index.

javascript
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const array3 = ['x', 'y', 'z'];

const result = zip(array1, array2, array3);
console.log(result); // [[1, 'a', 'x'], [2, 'b', 'y'], [3, 'c', 'z']]
Zipping multiple arrays

πŸ§ͺPractice Coding Problem: Array Zipper

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You are tasked with implementing a function zipArrays that takes two arrays and returns a new array by interleaving elements from the input arrays. If one array is longer than the other, the remaining elements should be appended to the result.

Problem (JavaScript)

javascript
/**
* Zip two arrays by interleaving their elements.
* @param {Array} arr1 - The first array.
* @param {Array} arr2 - The second array.
* @returns {Array} - The zipped array.
*/
function zipArrays(arr1, arr2) {
  // > > > πŸ‘‰ Write code here πŸ‘ˆ < < <
}

// Example usage:
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c', 'd'];

const zippedArray = zipArrays(array1, array2);
console.log(zippedArray); // Expected output: [1, 'a', 2, 'b', 3, 'c', 'd']
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
/**
* Zip two arrays by interleaving their elements.
* @param {Array} arr1 - The first array.
* @param {Array} arr2 - The second array.
* @returns {Array} - The zipped array.
*/
function zipArrays(arr1, arr2) {
  const zipped = [];
  const maxLength = Math.max(arr1.length, arr2.length);

  for (let i = 0; i < maxLength; i++) {
      if (i < arr1.length) zipped.push(arr1[i]);
      if (i < arr2.length) zipped.push(arr2[i]);
  }

  return zipped;
}
Solution Code

Whether you prefer concise functional programming or more traditional approaches, the goal remains the same – efficiently combining arrays element-wise.

Keep zipping through 🀐🀏, and happy coding! πŸš€πŸ’»

Contact

Feel free to reach out!