How to create a two-dimensional array in TypeScript?


A two-dimensional array in TypeScript is an array of arrays, or a matrix, which can be used to represent a table of data, a chess board, or any other type of grid.

Two-dimensional arrays are useful when working with a data grid, such as a table or a chessboard. They allow you to store and manipulate data in a structured way and access elements using a pair of indices.

Create a two-dimensional array

To create a two-dimensional array in TypeScript, users can use an array literal with the desired dimensions, like this −

Syntax

Users can follow the syntax below to create a two-dimensional array using Typescript.

let array_name:datatype[ ][ ] = [ [value1,value2,value3], [val1,val2,val3] ]; 
let element = array_name[row][col];

In the above syntax, we have created the 2D array named array_name. The datatype represents the data type of the two-dimensional array, and the values1, value2, etc., represent the array's values. Also, users can see how we can use the row and col to access values from the 2D array.

Example 1

In the example below, we have created the two-dimension array of strings. After that, we used the for-loop to initialize the array by iterating through it. Users can see that we are using the ASCII values to initialize the array.

In the output, users can observe how the 2D array is initialized. Also, users can use the row and column index to access the array element from a particular position.

let rows: number = 3;
let cols: number = 3;
let arr: string[][] = [];
for (let i = 0; i < rows; i++) {
   arr[i] = [];
   for (let j = 0; j < cols; j++) {
      arr[i][j] = String.fromCharCode(65 + i) + (j + 1);
   }
}
console.log(arr);

On compiling, it will generate the following JavaScript code −

var rows = 3;
var cols = 3;
var arr = [];
for (var i = 0; i < rows; i++) {
   arr[i] = [];
   for (var j = 0; j < cols; j++) {
      arr[i][j] = String.fromCharCode(65 + i) + (j + 1);
   }
}
console.log(arr);

Output

The above code will produce the following output −

[ [ 'A1', 'A2', 'A3' ],
  [ 'B1', 'B2', 'B3' ],
  [ 'C1', 'C2', 'C3' ] ]

Example 2

In this example, we have created a function called "getCarMatrix" that returns a two-dimensional array of cars. We use the type "Car" with properties such as make, model, and year of the car.

We initialize the "carMatrix" variable with two sets of cars. The first set has two cars, a Toyota Camry and a Ford Fiesta, and the second set has two cars, a Honda Civic and a Chevy Malibu. We return this "carMatrix" from the function and log it on the console.

// This defines a type "Car" with three properties: make, model, and year
type Car = {
   make: string;
   model: string;
   year: number;
};

// function to return a two-dimensional array of cars
function getCarMatrix(): Car[][] {
   // Initialize the car matrix with two sets of cars
   const carMatrix: Car[][] = [
      [
         { make: 'Toyota', model: 'Camry', year: 2020 },
         { make: 'Ford', model: 'Fiesta', year: 2022 }
      ],[
         { make: 'Honda', model: 'Civic', year: 2019 },
         { make: 'Chevy', model: 'Malibu', year: 2021 }
      ]
   ];
   return carMatrix;
}
console.log(getCarMatrix());

On compiling, it will generate the following JavaScript code −

// function to return a two-dimensional array of cars
function getCarMatrix() {

   // Initialize the car matrix with two sets of cars
   var carMatrix = [
      [
         { make: 'Toyota', model: 'Camry', year: 2020 },
         { make: 'Ford', model: 'Fiesta', year: 2022 }
      ],[
         { make: 'Honda', model: 'Civic', year: 2019 },
         { make: 'Chevy', model: 'Malibu', year: 2021 }
      ]
   ];
   return carMatrix;
}
console.log(getCarMatrix());

Output

The above code will produce the following output −

[ [ { make: 'Toyota', model: 'Camry', year: 2020 },
    { make: 'Ford', model: 'Fiesta', year: 2022 } ],
  [ { make: 'Honda', model: 'Civic', year: 2019 },
    { make: 'Chevy', model: 'Malibu', year: 2021 } ] ]

You might also use a two-dimensional array to represent a chess board, where each array element represents a square on the board, and its value indicates the piece that occupies it. You could then use the array to check for legal moves, check for checkmate, or perform other operations on the board.

Overall, two-dimensional arrays are a useful data structure for storing and manipulating data grids in TypeScript.

Updated on: 20-Jan-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements