Languages
[Edit]
EN

JavaScript - zip two arrays of the same length

0 points
Created by:
Kadeem-Craig
516

In this article, we would like to show you how to zip two arrays of the same length using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

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

var result = array1.map(function(element, index) {
    return [element, array2[index]];
});

console.log(JSON.stringify(result));

 

Modern JavaScript syntax

In this example, we present how to zip two arrays of the same length into 2D array using map() method with modern JavaScript syntax.

// ONLINE-RUNNER:browser;

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

const result = array1.map((element, index) => [element, array2[index]]);

console.log(JSON.stringify(result));

 

References

  1. Array.prototype.map() - JavaScript | MDN

Alternative titles

  1. JavaScript - zip two arrays of the same length into one 2D array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join