How to Zip Two Arrays in JavaScript
"Zipping" is the process of combining two or more arrays by merging their elements pairwise. For example, zipping [1, 2, 3] and ['a', 'b', 'c'] would result in [[1, 'a'], [2, 'b'], [3, 'c']]. This is a common operation in data processing, similar to Python's built-in zip() function. While JavaScript does not have a native zip() method, you can easily create this functionality.
This guide will teach you how to write a reusable zip function that can handle arrays of both equal and unequal lengths, using the modern and idiomatic Array.from() method.
The Core Problem: Combining Arrays Pairwise
The goal is to take two arrays and create a new array of pairs, where each pair contains one element from each of the original arrays at the same index.
For example, how to combine two arrays into pairs?
// Problem: How to combine these two arrays into pairs?
const keys = ['id', 'name', 'role'];
const values = [101, 'Alice', 'Admin'];
// Desired Result: [['id', 101], ['name', 'Alice'], ['role', 'Admin']]
This resulting structure is useful for many tasks, including creating a Map object directly (new Map(zippedArray)).
The Core Method: Array.from() with a Mapping Function
The most concise and modern way to zip arrays is to determine the length of the final array and then build it using Array.from().
A solution is this reusable zip function that handles the entire process.
/**
* Zips two arrays together into an array of pairs.
* The zipping stops at the length of the shorter array.
* @param {Array} arr1 - The first array.
* @param {Array} arr2 - The second array.
* @returns {Array<Array>} An array of [arr1_element, arr2_element] pairs.
*/
function zip(arr1, arr2) {
const length = Math.min(arr1.length, arr2.length);
return Array.from({ length }, (_, index) => {
return [arr1[index], arr2[index]];
});
}
// Example Usage:
const keys = ['id', 'name', 'role'];
const values = [101, 'Alice', 'Admin'];
const zipped = zip(keys, values);
console.log(zipped);
// Output: [ [ 'id', 101 ], [ 'name', 'Alice' ], [ 'role', 'Admin' ] ]
How the zip Function Works
Let's break down the zip function:
-
const length = Math.min(arr1.length, arr2.length);This is a crucial first step. It ensures that we only zip as many elements as are present in the shorter of the two arrays. This prevents us from getting pairs withundefinedvalues if the arrays are of different lengths. -
Array.from({ length }, ...)This is a powerful pattern. We are creating a new array of a specificlength. The first argument,{ length }, is an "array-like" object that tellsArray.fromhow long the new array should be. -
(_, index) => [arr1[index], arr2[index]]This is the mapping function thatArray.fromexecutes for each index from0up tolength - 1._: The first argument is the value of the element, which isundefinedin this case, so we use_to signify that we are ignoring it.index: The current index being processed (0, then1, then2, etc.).[arr1[index], arr2[index]]: For each index, we create a new two-element array (a "pair") by taking the element fromarr1at that index and the element fromarr2at the same index.
Handling Arrays of Different Lengths
The zip function provided above is intentionally designed to stop when the shortest array runs out of elements. This is the standard behavior of zipping functions in most other programming languages and is generally the most predictable and useful behavior.
For example, what happens when the arrays have different lengths?
const shortArray = [1, 2];
const longArray = ['a', 'b', 'c', 'd'];
Solution: ur zip function correctly handles this by stopping at the length of shortArray.
function zip(arr1, arr2) {
const length = Math.min(arr1.length, arr2.length);
return Array.from({ length }, (_, index) => [arr1[index], arr2[index]]);
}
const shortArray = [1, 2];
const longArray = ['a', 'b', 'c', 'd'];
const zipped = zip(shortArray, longArray);
console.log(zipped);
// Output: [ [ 1, 'a' ], [ 2, 'b' ] ] (The 'c' and 'd' are ignored)
If you need to include all elements and pad the missing spots with undefined, you would change Math.min to Math.max. However, this is a less common requirement. The "shortest-array" logic is the standard implementation.
Conclusion
While JavaScript doesn't have a built-in zip() method, you can easily create a powerful and reusable zip function using modern array methods.
- The
Array.from()method, combined with a mapping function, provides the most concise and readable way to zip two arrays. - The best practice is to zip only up to the length of the shorter of the two arrays, which you can determine using
Math.min(). This avoids unintendedundefinedvalues in your result.
By using this simple zip function, you can elegantly combine arrays for a wide variety of data transformation tasks.