I'm currently working on a TypeScript code that transposes an M x N matrix:
private transpose(a: number[][]): number[][] {
let m: number = a.length;
let n: number = a[0].length;
let b: number[][] = [[]]; // Attempted without "[[]]"
for (let i: number = 0; i < m; i++) {
for (let j: number = 0; j < n; j++) {
b[j][i] = a[i][j]; // Encountering an Error
}
}
return b;
}
Unfortunately, I am facing the following error:
Uncaught (in promise): TypeError: Cannot set property '0' of undefined
Is there a correct way to initialize the 2D array?
P.S. I have already tried using for..in
, but it still presents issues
Any thoughts or solutions?