Python zip 函式的 JavaScript 等效值


我們需要編寫一個 Python zip 函式對應的 JavaScript 等效函式。也就是說,給定多個長度相等的陣列,我們需要建立一個配對陣列。

例如,如果我有三個如下所示的陣列 -

const array1 = [1, 2, 3];
const array2 = ['a','b','c'];
const array3 = [4, 5, 6];

輸出陣列應該是 -

const output = [[1,'a',4], [2,'b',5], [3,'c',6]]

因此,我們編寫此函式 zip() 的程式碼。我們可以使用 reduce() 方法或 map() 方法,還可以使用簡單的巢狀 for 迴圈來完成此操作,但這裡我們將使用巢狀 forEach() 迴圈。

示例

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));

輸出

控制檯中的輸出將是 -

[ [ 1, 'a', 4 ], [ 2, 'b', 5 ], [ 3, 'c', 6 ] ]

更新日期: 2020 年 8 月 25 日

1K+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告