Home >Web Front-end >JS Tutorial >How to Zip Two Arrays in JavaScript?

How to Zip Two Arrays in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 18:17:15371browse

How to Zip Two Arrays in JavaScript?

Zipping Arrays in JavaScript

Zipping two arrays in JavaScript involves pairing elements from both arrays into a new array of tuples. This can be achieved using the map method, which creates a new array populated with the results of a provided callback function executed for each element of the original array.

Implementation:

To zip the arrays a and b as per the example provided, you can use the following code:

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

var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c);

Explanation:

The map method iterates over each element in a and calls the provided callback function with the current element and its index. Inside the callback function, we create a tuple by pairing the current element of a with the element at the same index in b. The result of this operation is then stored in a new array c.

Output:

The output of the provided code will be:

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

which matches the desired result.

The above is the detailed content of How to Zip Two Arrays 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