 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Transpose of a two-dimensional array - JavaScript
Transpose
The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). We can transpose a matrix (2-D array) by switching its rows with its columns.
Let’s say the following is our 2d array −
const arr = [ [1, 1, 1], [2, 2, 2], [3, 3, 3], ];
Let’s write the code for this function −
Example
Following is the code −
const arr = [    [1, 1, 1],    [2, 2, 2],    [3, 3, 3], ]; const transpose = arr => {    for (let i = 0; i < arr.length; i++) {       for (let j = 0; j < i; j++) {          const tmp = arr[i][j];          arr[i][j] = arr[j][i];          arr[j][i] = tmp;       };    } } transpose(arr); console.log(arr); Output
The output in the console: −
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
Advertisements
 