How to use JavaScript Zip Function with two or more Arrays?

Learn how to use the jszip or the JavaScript zip function to combine multiple arrays into a single array.

This article provides easy-to-follow instructions and examples to help you understand and utilize this powerful tool effectively.

So if you’re struggling with how to use the zip in js or JavaScript, continue reading!

What is “zip” function?

The zip() function combines the values from a given array with the values from the original collection at a specific index.

To accomplish this, the array is first converted into a collection, and then the function is applied.

What is JavaScript “zip” function?

JavaScript does not have a built-in zip function like Python does. However, you can create a similar function using JavaScript’s array methods.

The zip function as what we mentioned above, it is used to combine the values of multiple arrays at a given index.

For instance, if you have three arrays that look like this:

let array1 = [10, 20, 30, 40, 50];
let array2 = ['v','w','x','y','z'];
let array3 = [60, 70, 80, 90, 100];

The expected output would be:

let outputArray = [[10,'v',60], [20,'w',70], [30,'x',80], [40, 'y' 90], [50 'z' 100]]

So since JavaScript doesn’t have a built-in zip function, yet there’s an alternative way to create similar functions with the help of using the map.

Use the Array.map() method

You can use the Array.map() method to go through the first array and perform actions on each element.

For example:

let arr1 = [10, 20, 30];

let arr2 = ['it', 'source', 'code'];

const result = arr1.map((element, index) => {
  return [element, arr2[index]];
});

console.log(result);

Output:

[ [ 10, 'it' ], [ 20, 'source' ], [ 30, 'code' ] ]

The function we pass to Array.map() is called for each element of the first array. We use the index parameter and return a new array with elements from both arrays.

This creates a two-dimensional array with subarrays representing pairs of corresponding elements. The code can be simplified using an implicit return statement.

For example:

let arr1 = [10, 20, 30];

let arr2 = ['it', 'source', 'code'];

const result = arr1.map((element, index) => [
  element,
  arr2[index],
  
]);

console.log(result);

Output:

[ [ 10, 'it' ], [ 20, 'source' ], [ 30, 'code' ] ]

How to create a zip function in JavaScript?

Here’s an example of how you can create a zip function in JavaScript. This function takes multiple arrays as arguments and returns a result based on the length of the shortest array.

const zip = (...arrays) => {
  const length = Math.min(...arrays.map(a => a.length));
  return [...Array(length).keys()].map(i => arrays.map(a => a[i]));
}

This function takes multiple arrays as arguments using the spread operator (…). It finds the length of the shortest array using Math.min and Array.prototype.map (…arrays.map).

Then, it generates an array of indices using Array.from and Array.prototype.keys.

By mapping over these indices, it creates an array of merged values using Array.prototype.map.

How to use JavaScript “zip” function with two or more Arrays?

If you’re still confused about how to use jszip, here’s the following solution for you.

Solution 1: Use the Math.max() method

Here’s the solution for the example above that we illustrate:

let array1 = [10, 20, 30, 40, 50];
let array2 = ['v','w','x','y','z'];
let array3 = [60, 70, 80, 90, 100];

const zip = (...arrays) => {
  const length = Math.min(...arrays.map(a => a.length));
  return [...Array(length).keys()].map(i => arrays.map(a => a[i]));
}

const result = zip(array1, array2, array3);
console.log(result);

In this solution, we define a zip function, as explained earlier. We then use this zip function by passing three arrays (array1, array2, and array3) as arguments.

The resulting array, stored in the variable “result,” contains merged values from the input arrays.

Output:

[
  [ 10, 'v', 60 ],
  [ 20, 'w', 70 ],
  [ 30, 'x', 80 ],
  [ 40, 'y', 90 ],
  [ 50, 'z', 100 ]
]

Here’s another example of JavaScript “zip” function with two or more Arrays:

const zip = (...arrays) => {
  const length = Math.min(...arrays.map(a => a.length));
  return [...Array(length).keys()].map(i => arrays.map(a => a[i]));
}

const array1 = [85, 90, 95];
const array2 = ['English', 'Math', 'Science'];
const array3 = [90, 95, 99];

const result = zip(array1, array2, array3);
console.log(result); 

Output:

[ [ 85, 'English', 90 ], [ 90, 'Math', 95 ], [ 95, 'Science', 99 ] ]

Solution 2: Use the Array.forEach method

To zip two arrays in JavaScript, you can utilize the forEach() method. It enables you to iterate over each element of the arrays, access their corresponding values, and create a merged array efficiently.

For example:

function zip(array1, array2) {
  const zipped = [];

  array1.forEach((element, index) => {
    zipped.push([element, array2[index]]);
  });

  return zipped;
}

const array1 = [90, 95, 99];
const array2 = ['English', 'Math', 'Science'];

const output = zip(array1, array2);

console.log(output);

Output:

[ [ 90, 'English' ], [ 95, 'Math' ], [ 99, 'Science' ] ]

Solution 3: Use for loop

You can also combine two arrays into one using a simple for loop. This involves iterating over both arrays simultaneously, accessing their respective elements, and creating a new array that merges the values together.

For example:

function zip(array1, array2) {
  const zipped = [];

  for (let index = 0; index < array1.length; index++) {
    zipped.push([array1[index], array2[index]]);
  }

  return zipped;
}

const array1 = [91, 92, 93];
const array2 = ['English', 'Math', 'Science'];

const output = zip(array1, array2);

console.log(output);

Output:

[ [ 91, 'English' ], [ 92, 'Math' ], [ 93, 'Science' ] ]

Solution 4: use the Array.reduce method

Another way to zip two arrays in JavaScript is by using the Array.reduce method. This method allows you to iterate over the arrays, combine their values, and generate a new array as the output.

It provides a straightforward and effective approach for merging corresponding elements of the input arrays into a single array.

For example:

function zip(array1, array2) {
  return array1.reduce((accumulator, curr, index) => {
    return [...accumulator, [curr, array2[index]]];
  }, []);
}

const array1 = [95, 96, 97];
const array2 = ['English', 'Math', 'Science'];

const output = zip(array1, array2);

console.log(output);

Output:

[ [ 95, 'English' ], [ 96, 'Math' ], [ 97, 'Science' ] ]

Conclusion

In conclusion, this article explains how to achieve the functionality of the JavaScript zip function, which combines two or more Arrays.

While JavaScript doesn’t have a built-in zip function, the article presents different methods to accomplish this task using techniques like Array.map()Array.forEach(), for loops, and Array.reduce().

By understanding and applying these techniques, you can merge corresponding elements from multiple arrays effectively. 

It allows you to work with parallel arrays and manipulate data efficiently.

Overall, this article equips you with the necessary knowledge to utilize the zip functionality in JavaScript and enhance your data manipulation capabilities.

We are hoping that this article provides you with enough information that helps you understand the JavaScript Zip Function.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment