Skip to content

Create an array of pairs from multiple arrays of equal length – Zip function in JavaScript

Advertisements

Given multiple array of equal lendth, we need to pair the items of the same indexes and pair them. This is the equivalent of Python’s zip function in JavaScript.

const arr1 = [1, 2, 3];
const arr2 = ['one','two','three'];

// Output -- [[1,'one'],[2,'two'],[3,'three']]
const zip = (...arr) => {
   const zipped = [];
   arr.forEach((item, ind) => {
      item.forEach((i, index) => {
         if(!zipped[index]){
            zipped[index] = [];
         };
         if(!zipped[index][ind]){
            zipped[index][ind] = [];
         }
         zipped[index][ind] = i || '';
      })
   });
   return zipped;
};
console.log(zip(arr1, arr2)); //[[1,'one'],[2,'two'],[3,'three']]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.