Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript equivalent of Python\'s zip function
In this article, we will learn the JavaScript equivalent of Python's zip function. In Python, the zip() function is a convenient way to combine multiple arrays into a single iterable of tuples. However, JavaScript does not have a built-in equivalent for this functionality, so we need to implement our own.
Problem Statement
Given two or more arrays of equal length, implement a function in JavaScript that combines these arrays into a single array of arrays, where each inner array contains the elements from the input arrays at the corresponding positions.
Input
arr1 = [1, 2, 3], arr2 = ['a', 'b', 'c']
Output
[[1, 'a'], [2, 'b'], [3, 'c']]
Using for Loop and Map Method
The most straightforward approach uses a for loop to iterate over the indices and the map method to extract corresponding elements from each array.
Here's how it works:
- Iterate through indices using a for loop
- Use map to extract elements at the current index from all arrays
- Push the grouped elements into the result array
Example
function zip(...arrays) {
const length = arrays[0].length;
const result = [];
for (let i = 0; i < length; i++) {
const group = arrays.map(array => array[i]);
result.push(group);
}
return result;
}
// Example Usage
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const arr3 = [true, false, true];
console.log("Two arrays:", zip(arr1, arr2));
console.log("Three arrays:", zip(arr1, arr2, arr3));
Output
Two arrays: [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] Three arrays: [ [ 1, 'a', true ], [ 2, 'b', false ], [ 3, 'c', true ] ]
Using Array.from with Mapping
A more functional approach uses Array.from() to create the result array directly by mapping over the indices.
Example
const zip = (...arrays) => {
const minLength = Math.min(...arrays.map(arr => arr.length));
return Array.from({ length: minLength }, (_, index) =>
arrays.map(array => array[index])
);
};
// Example Usage
const numbers = [1, 2, 3, 4];
const letters = ['a', 'b', 'c']; // shorter array
const symbols = ['!', '@', '#', '$'];
console.log("Handles different lengths:", zip(numbers, letters, symbols));
Output
Handles different lengths: [ [ 1, 'a', '!' ], [ 2, 'b', '@' ], [ 3, 'c', '#' ] ]
Using Reduce Method
Another approach uses the reduce method to build the zipped array iteratively.
Example
const zipWithReduce = (...arrays) => {
const length = arrays[0].length;
return arrays[0].reduce((result, _, index) => {
result.push(arrays.map(array => array[index]));
return result;
}, []);
};
// Example Usage
const colors = ['red', 'green', 'blue'];
const fruits = ['apple', 'lime', 'berry'];
console.log("Using reduce:", zipWithReduce(colors, fruits));
Output
Using reduce: [ [ 'red', 'apple' ], [ 'green', 'lime' ], [ 'blue', 'berry' ] ]
Comparison Table
| Approach | Code Simplicity | Performance | Handles Different Lengths | Notes |
|---|---|---|---|---|
| for Loop + map | Simple | Efficient | Uses first array length | Most readable and straightforward |
| Array.from | Concise | Efficient | Yes, uses minimum length | More functional programming style |
| Reduce | Complex | Efficient | Uses first array length | Good for understanding reduce |
Key Points
- All approaches have O(n*m) time complexity, where n is the number of arrays and m is their length
- Space complexity is O(n*m) for storing the result
- The
Array.fromapproach handles arrays of different lengths by using the shortest array's length - Use rest parameters (
...arrays) to accept any number of input arrays
Conclusion
The for loop with map approach provides the best balance of readability and performance for implementing Python's zip function in JavaScript. Choose Array.from if you need to handle arrays of different lengths gracefully.
