Lakshya
Lakshya

Reputation: 352

Issue while transposing a matrix in javascript

I made a basic function which creates a new matrix which is rotated (transpose) of the input matrix.

let suggestionsArray = [[1,2,3,4],[5,6,7,8], [9,10,11,12], [13,14,15,16]]
            const keySize = suggestionsArray.length;
            const colSize = suggestionsArray[0].length
            let matrix = Array(colSize).fill(Array(keySize))
            console.log(matrix)
            for (let i = 0; i < keySize; i++) {
                for (let j = 0; j < colSize; j++) {
                    
                    matrix[j][i] = suggestionsArray[i][j]
                    console.log(j, i, matrix[j][i])
                }
            }
            console.log(matrix)
            return matrix

But the result matrix is

[
    [
        4,
        8,
        12,
        16
    ],
    [
        4,
        8,
        12,
        16
    ],
    [
        4,
        8,
        12,
        16
    ],
    [
        4,
        8,
        12,
        16
    ]
]

Which is not something I was expecting

I've ready playing around but and everything looked good to me but still the matrix comes up wrong.

Upvotes: 1

Views: 45

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

In case you are trying to "transpose" the matrix, then the following would do it:

let suggestionsArray = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
  [13, 14, 15, 16]
]
const matrix=suggestionsArray.reduce((ma,row,i)=>{
 row.forEach((cell,j)=>(ma[j]??=[])[i]=cell);
 return ma;
},[])

console.log(matrix)

Upvotes: 2

Related Questions