Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

JavaScript เทียบเท่ากับฟังก์ชัน zip ของ Python


เราต้องเขียนฟังก์ชัน JavaScript ที่เทียบเท่ากับฟังก์ชัน zip ของ Python นั่นคือ ให้อาร์เรย์หลายอาร์เรย์มีความยาวเท่ากัน เราจำเป็นต้องสร้างอาร์เรย์ของคู่

ตัวอย่างเช่น หากฉันมีสามอาร์เรย์ที่มีลักษณะเช่นนี้ −

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() กัน เราสามารถทำได้หลายวิธี เช่น ใช้วิธีการ thereduce() หรือ map() หรือโดยการใช้ nested for loops แบบง่าย แต่ในที่นี้ เราจะทำการ bedoing ด้วย forEach() loop ที่ซ้อนกัน

ตัวอย่าง

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 ] ]