Map and Reduce
This approach utilizes higher-order functions like map and reduce for a more concise and potentially more readable solution.
Example: JavaScript program for transposing a matrix using functional programming by utilizing map functions to transpose rows and columns within a given 2D matrix.
Javascript
function transpose2(matrix) { return matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]) ); } const exampleMatrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; const transposedMatrix = transpose2(exampleMatrix); console.log(transposedMatrix); |
Output
[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
JavaScript Program to Find the Transpose
The transpose of a matrix in linear algebra is a new matrix that is produced by flipping its rows and columns. Most numerical and mathematical applications depend on this technique.
There are several approaches available to find the transpose of the matrix in JavaScript, which are as follows:
Table of Content
- Nested Loops
- Map and Reduce
- Spread Operator and Reduce