How to Zip Two or More Arrays in JavaScript – A Comprehensive Guide


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']]

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 array2 = ['a', 'b', 'c'];
const result = zipArrays(array1, array2);
console.log(result); // [[1, 'a'], [2, 'b'], [3, 'c']]

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']]

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']]

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']]

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']]

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']]

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']]

πŸ§ͺ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.

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']
Please attempt before seeing the Answer:
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;
}

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! πŸš€πŸ’»

Scroll to Top