JavaScript equivalent of Python's zip function

JavascriptObject Oriented ProgrammingWeb Development

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 ] ]
raja
Published on 25-Aug-2020 10:12:22
Advertisements