Spread Operator and Reduce
In particular, for larger matrices, this method may be more efficient because it makes use of the spread operator and reduces. The reduce function accumulates the transposed matrix starting with an empty array now for each row in the original matrix, The spread operator (…) creates a copy of the current transposed array and the map function iterates through each element of the current row. It then retrieves the corresponding element from the same column index in each row of the original matrix using matrix[colIndex][row.indexOf(_)]. The mapped elements for the current row are then added to the transposed array. The final reduce call returns the accumulated to the transposed matrix.
Example: JavaScript program for transposing a matrix: A concise example demonstrating the transpose function applied to a 2D matrix to interchange rows and columns.
Javascript
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; function transpose(matrix) { return matrix[0].map((_, i) => { return matrix.reduce((acc, row) => [...acc, row[i]], []) }); } const transposedMatrix = transpose(matrix); console.log(transposedMatrix); |
[ [ 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