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.
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:
- Uses the array.map()
- Using the nested loop
- Using reduce() Method
- Using Zip and Unzip
Contact Us