Handling Multi-Dimensional Array Initialization in TypeScript with Dynamic Sizes
I'm refactoring my project and I'm trying to implement I'm dealing with I'm stuck on something that should probably be simple. I'm struggling with initializing a multi-dimensional array in TypeScript where the dimensions are determined at runtime. I want to create a 2D array of integers based on user input, but I keep running into issues with types and sizes. For instance, if a user inputs 3 for rows and 4 for columns, I want to create an array like `let myArray: number[][] = new Array(3).fill(0).map(() => new Array(4).fill(0));`. However, when I try to access an element like `myArray[0][0]`, I sometimes get a runtime behavior, especially if I haven't properly initialized the array. I also encountered an scenario where using `new Array()` without filling it would lead to frames of undefined values when trying to map through it. Here's a sample of my current implementation: ```typescript function create2DArray(rows: number, columns: number): number[][] { return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); } const myArray = create2DArray(3, 4); console.log(myArray); console.log(myArray[0][0]); // This works fine ``` However, I noticed that if I change the way I fill the array, like using `new Array(rows).fill([])`, I end up with multiple references to the same inner array. This leads to unintended modifications across rows if I change one of the inner arrays. I'd like to understand the correct way to initialize a multi-dimensional array in a way that avoids these pitfalls. Is there a better or more idiomatic way to do this in TypeScript, especially when the array sizes can change dynamically based on user input? Any insights would be greatly appreciated! Also, I'm using TypeScript version 4.5.2. Any ideas what could be causing this? This is part of a larger API I'm building. Any ideas how to fix this? This issue appeared after updating to Typescript 3.9. I appreciate any insights!