Home > Backend Development > Python Tutorial > Is There a JavaScript Equivalent to Python's zip Function?

Is There a JavaScript Equivalent to Python's zip Function?

Mary-Kate Olsen
Release: 2024-12-13 19:43:14
Original
270 people have browsed it

Is There a JavaScript Equivalent to Python's zip Function?

Javascript Equivalent of Python's zip Function

In Python, the zip function combines multiple iterables into a single iterable of tuples, where each tuple contains the corresponding elements from the input iterables. Is there a similar function available in Javascript?

Javascript Implementation

Yes, there is an equivalent zip function in Javascript. It takes an array of arrays as its argument and returns an array of arrays, where each inner array contains the corresponding elements from the input arrays. For example, if you have three arrays:

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

The following code will create an array of pairs:

const outputArray = array1.map((_, i) => [array1[i], array2[i], array3[i]]);
Copy after login

The output array will be:

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

ES6 Version

In ES6, you can use the following syntax:

const zip = (...rows) => rows[0].map((_, c) => rows.map(row => row[c]));
Copy after login

Additional Features

The Javascript zip function can be modified to mimic the behavior of Python's zip function and its extensions. For instance, you can create functions that:

  • Assume arrays of unequal length and silently disregard longer arrays.
  • Insert undefined values for missing elements in arrays.
  • Handle iterables, such as strings and ranges.

Addendum: Handling Iterables

To handle iterables, you can define an iterView function that converts an iterable to an array equivalent. Alternatively, you can use the following function:

const zip = arrays => Array.apply(null, Array(arrays[0].length)).map((_, i) => arrays.map(array => array[i]));
Copy after login

The above is the detailed content of Is There a JavaScript Equivalent to Python's zip Function?. 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