Home > Web Front-end > JS Tutorial > How Can I Zip Two Arrays Together in JavaScript?

How Can I Zip Two Arrays Together in JavaScript?

Patricia Arquette
Release: 2024-12-06 06:22:14
Original
773 people have browsed it

How Can I Zip Two Arrays Together in JavaScript?

Zipping Arrays in JavaScript

Zipping two arrays involves combining corresponding elements from both arrays into a single array. To achieve this, you can leverage JavaScript's built-in array methods.

Using the map method:

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

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

console.log(c); // [[1, 'a'], [2, 'b'], [3, 'c']]
Copy after login

In this code, the map method iterates over the elements of array 'a' and for each element, it creates an array containing that element paired with the corresponding element from array 'b'. The resulting array 'c' is a zip of arrays 'a' and 'b'.

Alternatively, you can use a combination of the forEach and push methods:

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

a.forEach(function(e, i) {
  c.push([e, b[i]]);
});

console.log(c); // [[1, 'a'], [2, 'b'], [3, 'c']]
Copy after login

This code also produces the same result as the previous example, but it uses a loop with a push operation to build the zipped array.

By utilizing these methods, you can effectively zip any two arrays to create a new array containing pairs of corresponding elements.

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