কম্পিউটার টিউটোরিয়াল

JavaScript-এ Python-এর zip ফাংশনের সমতুল্য


আমাদের 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() মেথড বা সিম্পল নেস্টেড ফর লুপ দিয়ে, কিন্তু এখানে আমরা নেস্টেড 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 ] ]

  1. জাভাস্ক্রিপ্ট Number() ফাংশন

  2. জাভাস্ক্রিপ্টে Const এবং Let এর পার্থক্য

  3. জাভাস্ক্রিপ্টে ফাংশন প্রোটোটাইপ

  4. জাভাস্ক্রিপ্টে ফাংশন বরোइং (Function Borrowing)