Sometimes, we want to initialize a multidimensional array with TypeScript.
In this article, we’ll look at how to initialize a multidimensional array with TypeScript.
How to initialize a multidimensional array with TypeScript?
To initialize a multidimensional array with TypeScript, we can use the array fill
and map
methods.
For instance, we write
const n = 10;
const palindrome: boolean[][] = new Array(n)
.fill(false)
.map(() => new Array(n).fill(false));
to create a 10×10 palindrome
array that’s filled with false
everywhere.
We do that by using Array
with n
to create an array with length 10.
And then we call fill
to fill that with false
.
Then we call map
with a callback that map the entries in the array to arrays with 10 false
entries.
Conclusion
To initialize a multidimensional array with TypeScript, we can use the array fill
and map
methods.