আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি টু-ডাইমেনশনাল অ্যারে নেবে এবং এর ট্রান্সপোজড (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 ] ]