
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
JavaScript equivalent of Python's zip function
We have to write the JavaScript equivalent function of Python's zip function. That is, given multiple arrays of equal lengths, we are required to create an array of pairs.
For instance, if I have three arrays that look like this −
const array1 = [1, 2, 3]; const array2 = ['a','b','c']; const array3 = [4, 5, 6];
The output array should be −
const output = [[1,'a',4], [2,'b',5], [3,'c',6]]
Therefore, let’s write the code for this function zip(). We can do this in many ways like using the reduce() method or the map() method or by using simple nested for loops but here we will be doing it with nested forEach() loop.
Example
const array1 = [1, 2, 3]; const array2 = ['a','b','c']; const array3 = [4, 5, 6]; const zip = (...arr) => { const zipped = []; arr.forEach((element, ind) => { element.forEach((el, index) => { if(!zipped[index]){ zipped[index] = []; }; if(!zipped[index][ind]){ zipped[index][ind] = []; } zipped[index][ind] = el || ''; }) }); return zipped; }; console.log(zip(array1, array2, array3));
Output
The output in the console will be −
[ [ 1, 'a', 4 ], [ 2, 'b', 5 ], [ 3, 'c', 6 ] ]
- Related Articles
- Python zip() Function
- Equivalent of Ruby's each cons in JavaScript
- Zip function in Python to change to a new character set.
- JavaScript's Boolean function?
- Kotlin equivalent of Java's equalsIgnoreCase
- What's the Kotlin equivalent of Java's String[]?
- Working with zip files in Python
- zipapp - Manage executable Python zip archives
- C# equivalent to Java's Thread.setDaemon?
- What is the PHP equivalent of MySQL's UNHEX()?
- Work with ZIP archives in Python (zipfile)
- Python import modules from Zip archives (zipimport)
- The equivalent of SQL Server function SCOPE_IDENTITY() in MySQL?
- Equivalent to matlab's imagesc in Matplotlib
- How to zip a folder recursively using Python?

Advertisements