Multidimensional arrays
- TypeScript course
- Beginner
- Lesson 14/89
- 4 min
Learn to define nested arrays.
Multidimensional arrays
A multidimensional array is a structure where an array contains other arrays. The nested array type is written as number[][], meaning "an array of number arrays". It is used for matrix or table-like data.
let matris: number[][] = [
[1, 2, 3],
[4, 5, 6]
];
console.log(matris[0][1]); // 2Accessing nested elements
To access an element in nested arrays, two brackets are used. matris[0] gives the first row, and matris[0][1] gives the second element of the first row. TypeScript type-checks even when rows and columns differ in count.
let tablo: string[][] = [
["ad", "soyad"],
["Ali", "Yılmaz"]
];
console.log(tablo[1][0]); // "Ali"Practice Number matrix
Define a 2x3 matrix named matris of type number[][]: first row [1, 2, 3], second row [4, 5, 6]. Then print the second row with console.log.
Starter code
// 2x3 sayı matrisi tanımla, ikinci satırı yazdırSample solution
let matris: number[][] = [
[1, 2, 3],
[4, 5, 6]
];
console.log(matris[1]);Expected output
[ 4, 5, 6 ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the `string[][]` type express?
- An outer array whose each element is a string array Correct answer
- A single string value
- A readonly string array
- A fixed set of two strings
Explanation: `string[][]` defines an outer array whose each element is a `string[]`; this creates nested string arrays.
2 Write a nested array type
let koordinatlar: number____ = [[0, 0], [3, 4]];
let koordinatlar: number[][] = [[0, 0], [3, 4]];
Explanation: `number[][]` specifies an array of number arrays; each element must be of type `number[]`.
3 Multidimensional concepts
| Term | Meaning |
|---|---|
number[][] |
A number matrix |
string[][] |
A string table |
matris[0] |
The first row |
matris[0][1] |
The second element of the first row |