Home >Web Front-end >JS Tutorial >How Can I Replicate Python's Zip Function in JavaScript?

How Can I Replicate Python's Zip Function in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 18:58:10531browse

How Can I Replicate Python's Zip Function in JavaScript?

Javascript Equivalents of Python's Zip Function

Python's zip function can be replicated in JavaScript using various approaches. Let's explore two common methods:

1. Array Mapping

This method assumes the input arrays are of equal length and involves mapping the first array to create pairs with corresponding elements from the other arrays.

function zip(...arrays) {
  return arrays[0].map((_, i) => arrays.map((array) => array[i]));
}

Example:

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

const zippedArray = zip(array1, array2, array3);

console.log(zippedArray); // [[1, 'a', 4], [2, 'b', 5], [3, 'c', 6]]

2. Array.apply and Array Mapping

This method handles both equal and unequal length arrays, returning undefined for missing values.

function zip(...arrays) {
  const longest = arrays.reduce((a, b) => (a.length > b.length ? a : b), []);

  return Array.apply(null, Array(longest.length)).map((_, i) =>
    arrays.map((array) => array[i])
  );
}

Example:

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

const zippedArray = zip(array1, array2, array3);

console.log(zippedArray); // [[1, 'a', 4], [2, 'b', 5], [3, undefined, 6]]

Note: If you're using any of the above methods with arrays of unequal length, keep in mind that they aren't their own inverse. To mimic Python's zip(*[...]) idiom, use zip.apply(this, [...]).

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

Statement:
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