Home > Web Front-end > JS Tutorial > How to Implement Python's Zip Function in JavaScript?

How to Implement Python's Zip Function in JavaScript?

Mary-Kate Olsen
Release: 2024-12-26 17:33:13
Original
231 people have browsed it

How to Implement Python's Zip Function in JavaScript?

JavaScript Equivalent of Python's Zip Function

The Python Zip function is commonly used to combine multiple arrays of equal length into pairs, forming a new array. JavaScript provides a similar functionality through the implementation of the Array.prototype.map() method and a helper function. Here's how you can achieve this:

function zip(...arrays) {
  return arrays[0].map((_, i) => arrays.map(arr => arr[i]));
}
Copy after login

Let's illustrate how this function behaves:

Consider three arrays of equal length:

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
const array3 = [4, 5, 6];
Copy after login

Using our zip function:

const result = zip(array1, array2, array3);
Copy after login

The result would be as follows:

result = [[1, 'a', 4], [2, 'b', 5], [3, 'c', 6]];
Copy after login

It effectively pairs the corresponding elements from each array into a sub-array.

However, it's important to note that our JavaScript implementation doesn't have the same functionality as Python's zip function when handling unequal array lengths. In Python, the zip function combines arrays of unequal length and stops at the length of the shortest array. In our JavaScript implementation, it will exclude elements from the longer arrays that fall beyond the length of the shortest array.

The above is the detailed content of How to Implement Python's Zip Function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template