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

জাভাস্ক্রিপ্টে 2-D অ্যারের ট্রান্সপোজ (transpose) বের করা


আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি টু-ডাইমেনশনাল অ্যারে নেবে এবং এর ট্রান্সপোজড (transposed) অ্যারে রিটার্ন করবে।

কোডটি হবে −

পদ্ধতি ১: Array.prototype.forEach() ব্যবহার করে

const arr = [    [0, 1],    [2, 3],    [4, 5] ]; const transpose = arr => {    const res = [];    arr.forEach((el, ind) => {       el.forEach((elm, index) => {          res[index] = res[index] || [];          res[index][ind] = elm;       });    });    return res; }; console.log(transpose(arr));

পদ্ধতি ২: Array.prototype.reduce() ব্যবহার করে

const arr = [    [0, 1],    [2, 3],    [4, 5] ]; const transpose = arr => {    let res = [];    res = arr.reduce((acc, val, ind) => {       val.forEach((el, index) => {          acc[index] = acc[index] || [];          acc[index][ind] = el;       });       return acc;    }, [])    return res; }; console.log(transpose(arr));

দুটি পদ্ধতির কনসোলে আউটপুট −

[ [ 0, 2, 4 ], [ 1, 3, 5 ] ]

  1. জাভাস্ক্রিপ্টে অ্যারে খালি কীভাবে করবেন?

  2. জাভাস্ক্রিপ্টে অ্যারে খালি করার উপায়

  3. জাভাস্ক্রিপ্ট বেসিক অ্যারে মেথড: push, pop, shift, unshift, splice

  4. জাভাস্ক্রিপ্টে অ্যারেতে মিডিয়ান সূচক খুঁজে বের করা