Approach 2: Using the nested loop

  • Store a 2D array into a variable.
  • Replace every element in the array with its mirror image with respect to the diagonal of the array.

Example: This example creates a function that replaces every element with its mirror image to get the transpose of the array.  

Javascript
let array = [
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3],
];

console.log("[ [ " + array[0] 
    + " ] ], [ [ " + array[1] 
    + " ] ], [ [ " + array[2] 
    + " ] ]");

function transpose(mat) {
    for (let i = 0; i < mat.length; i++) {
        for (let j = 0; j < i; j++) {
            const tmp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = tmp;
        }
    }
}

function gfg_Run() {
    transpose(array);
    console.log("[ [ " + array[0] 
        + " ] ], [ [ " + array[1] 
        + " ] ], [ [ " + array[2] 
        + " ] ]");
}

gfg_Run();

Output
[ [ 1,1,1 ] ], [ [ 2,2,2 ] ], [ [ 3,3,3 ] ]
[ [ 1,2,3 ] ], [ [ 1,2,3 ] ], [ [ 1,2,3 ] ]

Transpose a two dimensional (2D) array in JavaScript

Given a 2D array (matrix) and the task is to get the transpose of the matrix using JavaScript.

We can do this by using the following methods:

Similar Reads

Approach 1: Uses the array.map()

Store a 2D array into a variable.Display the 2D array (matrix) content.Call map() method which provides a callback function single time for every element in an array, maintaining the order and returns a new array (transpose of the original array) from the results....

Approach 2: Using the nested loop

Store a 2D array into a variable.Replace every element in the array with its mirror image with respect to the diagonal of the array....

Approach 3: Using reduce() Method

We can use reduce() method and map() for transposing the array....

Approach 4: Using Zip and Unzip

By defining the helper functions for zipping and unzipping arrays, after it apply them to transpose the array....

Contact Us