Finding transpose of a 2-D array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a two-dimensional array and returns its transposed array.

The code for this will be −

Method 1: Using 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));

Method 2: Using 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));

The output in the console for both the methods will be −

[ [ 0, 2, 4 ], [ 1, 3, 5 ] ]
raja
Published on 09-Oct-2020 11:09:08
Advertisements