เราต้องเขียนฟังก์ชัน zip() ของ JavaScript ที่เทียบเท่ากับ 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() กัน เราสามารถทำได้หลายวิธี เช่น ใช้ reduce() หรือ map() หรือ for loop ท่อใน แต่นี่เราจะทำด้วย nested 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 ] ]