Open In App

Transpose a two dimensional (2D) array in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Example: This example uses the array.map() method 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() {
    array = array[0].map(
        (col, i) => array.map(row => row[i]));
 
    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 ] ]

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 ] ]

Approach 3: Using reduce() Method

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

Example:

Javascript




let array = [
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3],
];
let newArr = array.reduce((prev, next) =>
             next.map((item, i) =>
    (prev[i] || []).concat(next[i])
), []);
console.log(newArr);


Output

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


Last Updated : 13 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads