- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] ]
Advertisements