Create 2D Array
TypeScript/Array
A 2D array is also known as a matrix. It's arranged in a table-like structure that consists of rows and columns. In TypeScript, we can create 2D arrays in several ways, Array.from()
being one of the most elegant solutions.
The Array.from()
method creates a shallow-copied array from an array-like or iterable object. It accepts two main parameters:
- An iterable or array-like object to convert
- A optional mapping function that transforms each element
Here's a utility function that creates a 2D array with specified dimensions and initial values:
Debugging Tips: When working with 2D arrays, use console.table()
for better visualization.
Ref: Array.from()