Working with Arrays in TypeScript

In this post on Working with Arrays in TypeScript, I will explain how to use arrays in TypeScript with several examples. Like many other programming languages, TypeScript also supports arrays. Basically, arrays refer to a user-defined data type that contains multiple values. Usually, the values that an array contains, all belong to the same data type. However, TypeScript gives us the flexibility to create arrays having elements of different types.

Important Points Regarding Arrays in TypeScript

Like other programming languages, the index of a TypeScript array also starts with 0. Moreover, the array represents the contiguous memory locations. However, in TypeScript, it is mandatory to initialize an array before its use.

Creating an Array

There are two ways to create an array as shown below.

let array_name: data_type[] = [v1, v2, v3,...., vn]

As evident from the above syntax, the square bracket([]) denotes that the variable with array_name is a one-dimensional array. The initialization of values also uses square brackets in TypeScript. The comma-separated list v1, v2, v3, …, vn represents the values assigned to the array. Also, the size of the array depends on the total number of values in the initialization list. An example of an array declaration is given below.

let arr: number[] = [10, 20, 30, 40]
let names: string[] = ["ab", "bc", "cd", "de", "ef"]

The second way of creating arrays doesn’t use the data type. In fact, the initial values assigned to the array elements determine the data type of array, as shown in the following example. As evident from the initial values, the data type of array a1 is number.

let a1 = [1,2,3,4,5]

Examples on Working with Arrays in TypeScript

Example 1: The example given below is a basic example of using arrays in TypeScript. In this example, we create the two arrays arr, and arr1 using the declaration syntax described earlier. Also, this example demonstrates the use of forEach() function to display the elements of array.

let arr: number[]=[1,2,3,4]
console.log("Displaying the contents of a 1D array: ")
arr.forEach(function(v){
console.log(v)})

let arr1=[10,20,30,40,50]
console.log("1D array created using initial values only: ")
arr1.forEach(function(x){
console.log(x)})

Output:

Demonstrating 1D Array in TypeScript
Demonstrating 1D Array in TypeScript

Example 2: Creating a 2D Array in TypeScript

Following example shows the creation of two-dimensional arrays in TypeScript. As shown below, m1, m2, and m3 are 2D arrays representing matrices. In order to find the product of two matrices, m1 and m2, their size is taken as 4X2 and 2X4 respectively which gives a 4X4 product matrix.

let m1: number[][]=[[1,2],[3,4],[5,6],[7,8]]

console.log("Displaying a 2D array in TypeScript: ")
let str: string=""
for(let i=0;i<4;i++)
{
 for(let j=0;j<2;j++)
 {  
    str=str+m1[i][j]+" "
 }  
 console.log(str)
 str=""
}

console.log("Matrix Multiplication: ")
let m2:number[][]=[[9, 1, 2, 3], [4, 8, 6, 5]]
let m3:number[][]=[[0,0,0,0],[0,0,0,0],[0,0,0,0], [0,0,0,0]]

console.log("Let m1 be is 4X2 Matrix.")
console.log("Displaying m1 Matrix: ")
for(let i=0;i<4;i++)
{
 for(let j=0;j<2;j++)
 {  
    str=str+m1[i][j]+" "
 }  
 console.log(str)
 str=""
}

console.log("Let m2 be is 2X4 Matrix.")
console.log("Displaying m2 Matrix: ")
for(let i=0;i<2;i++)
{
 for(let j=0;j<4;j++)
 {  
    str=str+m2[i][j]+" "
 }  
 console.log(str)
 str=""
}


/* Find Matrix Product */
for(let i=0;i<4;i++)
{
 for(let j=0;j<4;j++)
 {
//    m3[i][j]=0
    for(let k=0;k<2;k++)
    {
      m3[i][j]+=m1[i][k]*m2[k][j]
    }  
 }  
}

console.log("Product of m1 and m2 is a 4X4 Matrix m3.")
console.log("Displaying m3 Matrix: ")
for(let i=0;i<4;i++)
{
 for(let j=0;j<4;j++)
 {  
    str=str+m3[i][j]+" "
 }  
 console.log(str)
 str=""
}

Output:

Matrix Multiplication In TypeScript
Matrix Multiplication In TypeScript

Generic Arrays in TypeScript

TypeScript also allows us to create generic arrays that may contain elements of different types. Basically, the generic array syntax lets you mix the values belonging to different types which could be the simple types such as number and string or a user-defined type. The syntax for creating generic arrays is given below:

let array_name: (type1|type2|type3|....|typen)[] = [v1, v2, v3, ...., vn]

Here type1, type2, type3, …. and typen are different data types and v1, v2, v3, …., and vn are values belonging to any of these types. Now, let us consider an example of generic arrays, as given in the following code:

Example 3: Creating a generic array

In this example, MyArr is ageneric array that may contain elements of type number, string, Item, and Person. Further, the example also demonstrates the use of instanceof operator, which determines whether the object has the type Item or Person. Then, the appropriate method of the corresponding class is called.

class Item
{
  iname: string;
  item_price: number;
  quantity: number;
  constructor(s1:string, a:number, b: number)
  {
     this.iname=s1
     this.item_price=a
     this.quantity=b
   }

   findValue():void{
       console.log("Item Name = "+this.iname+" Total amount = Rs."+this.item_price*this.quantity) 
    }
}

class Person
{
   pname: string
   work: string
   constructor(s1: string, s2: string)
   {
	this.pname=s1
        this.work=s2
   }
   showPerson():void
   {
      console.log(this.pname+" working as "+this.work)
   }
}


let MyArr:(number|string|Item|Person)[]=[21, 34, 33, new Item("Pen", 10, 23), new Person("Amit", "Carpenter"), new Person("Raju", "Plumber"), "de", new Item("Notebook", 35, 22), "ab", "bc"]

console.log("Array Elements: ")
MyArr.forEach(function(ob){

if(ob instanceof Item)
{
  ob.findValue()
}
else
{
   if(ob instanceof Person)
   {
      ob.showPerson()
   }
   else
   {
      console.log(ob)
   }
}
})

Output:

Generic Array Demo
Generic Array Demo

Summary

TypeScript language allow us to create arrays in a variety of ways which can be single-dimensional arrays or multi-dimensional arrays. Also, we have flexibility to mix the elements of different types in the same array, which is useful in many applications.


Related Topics

Introduction to Programming in TypeScript

Creating Classes in TypeScript

Leave a Comment

Your email address will not be published. Required fields are marked *