Open In App

JavaScript Equivalent to Python zip

Last Updated : 04 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we use zip() function to combine multiple iterables like lists into pairs or tuples. This is really helpful when we want to loop through two or more lists at the same time.

Python
a = [1, 2, 3]
b = ['a', 'b', 'c']

result = zip(a, b)
print(list(result)) 

Output
[(1, 'a'), (2, 'b'), (3, 'c')]

If we're using JavaScript, there's no direct zip() function but we can achieve the same result with a few methods.

Let's explore how we can do that in JavaScript starting with the simplest approach.

Using for loop to zip

This is simplest way to zip two arrays together. We'll loop through the arrays and pair up their elements manually.

JavaScript
let a = [1, 2, 3];
let b = ['a', 'b', 'c'];

let result = [];
for (let i = 0; i < a.length && i < b.length; i++) {
    result.push([a[i], b[i]]);
}

console.log(result);

Output
[ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ]

Other methods that we can use are:

Using map()

We can also use JavaScript map() method which is a bit cleaner and more modern than a for loop. This approach works if both arrays have the same length.

JavaScript
let a = [1, 2, 3];
let b = ['a', 'b', 'c'];

let result = a.map((value, index) => [value, b[index]]);

console.log(result); 

Output
[ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ]

Using reduce()

If we want to be more advanced, we can use reduce(). This method allows us to accumulate a result by combining elements from both arrays into pairs.

JavaScript
let a = [1, 2, 3];
let b = ['a', 'b', 'c'];

let result = a.reduce((acc, value, index) => {
    acc.push([value, b[index]]);
    return acc;
}, []);

console.log(result); 

Output
[ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ]
  • We used reduce() to accumulate the pairs. The acc variable starts as an empty array and gets filled with pairs of elements from a and b. At each step, we push the pair to the accumulator and return it to continue the process.

Handling Arrays of Different Lengths

What if the arrays are of different lengths? We need to stop when the shorter array ends. In Python, zip() automatically stops at the shortest array. We can do something similar in JavaScript using Math.min().

JavaScript
let a = [1, 2, 3];
let b = ['a', 'b'];

let result = [];
let length = Math.min(a.length, b.length);

for (let i = 0; i < length; i++) {
    result.push([a[i], b[i]]);
}

console.log(result); 

Output
[ [ 1, 'a' ], [ 2, 'b' ] ]

Next Article
Practice Tags :

Similar Reads