{

Typescript Array Tutorial with Examples


Typescript Array examples

Typescript Array: Learn with usage examples.

Array Object in Typescript

Arrays are the basics of any language. Arrays are used to store the multiple values under one collection name. Basically, in a web application, we will use Arrays for storing a list of objects list of JSON values, and custom entries as well as for storing primitive values by getting data from the database.

In typescripts arrays are objects. Elements from arrays can be retrieved by index.

Array Syntax declaration

var  variableArrayName[:Data-type];  
variableArrayName=[list of objects/elements]  
or   
var variableArrayName[:Array[Data-type]];  
variableArrayName=[list of objects/elements]  

variablename is a valid identifier An array is a keyword in typescript. datatype is a data type of data in an array

How do declare and initialize arrays in Typescript?

There are many ways we can declare an array in typescript.

Firstly, it declares a variable of type with square bracket syntax([])

var array1: string[];  

And initialize an array with the square brackets of values. Here, an empty array is assigned with values.

array1=[]

Both the above lines can be replaced with single-line syntax

var array1: string[]=[];

Secondly, arrays can be declare and initialized with Array type

var array2: string[] = new Array();  
var array3: string[] = Array();  
var array5: Array = new Array();  
var array6: Array = Array();

Thirdly, You can also declare and initialize an array using single line as seen below

var array1: string[] = ['one','two','three'];  

the above array holds values at index 0 - ‘one’, index 1- ‘two’, index 2- ‘three’.

we can also declare an array without data type and data type is inferred from assigned data. arrays will assume that the data type of array can be decided based on the values of an array.

we will see array examples to check the typeof of an array, length of an array, retrieve an element from an array.

var array1: string[] = ['one','two','three'];  
console.log(typeof array1) //returns object  
console.log(array1.length) //returns 3  
console.log(array1[0]) // returns 'one'  
console.log(array1[1]) // returns 'two'  
console.log(array1[2]) // returns 'three'  
console.log(array1[3]) // returns undefined  

How do declare Arrays of Objects?

In typescript, interface or classes are used to declare an object. let’s declare an class in typescript for employee

interface Employee{
  id:number,
  name:string
    constructor(_id:number, _name:string) {
    this.id = _id;
    this.name = _name;
  }

}

One way, Let’s declare an array of objects with the square bracket syntax

let emps: Employee[]=[];

Another way is, Declare an array with Array syntax

let emps1: Array<Emloyee>;

And also, declare an array using an array with a type of objects in it as seen below

let employees: Array<{ id: number, name: string }>;

finally, declare and initialize an array of objects using single statements

let emps: Employee[] =
  [new Employee(11, "John"), new Employee(12, "Eric")];

Similarly, initialization can be done by assigning json string objects as seen below

let emps: Employee[] =  [{
  id: 11,
  name: "John"
},
{
  id: 12,
  name: "Eric"
}
  ];

How do declare Arrays Strings?

we can also create Array Object using empty arrays or parameter constructor

var emps: string[] = new Array(2)    
emps.push('emp1')  
emps.push('emp2')  
emps.push('emp3')  
for(var i = 0;i<emps.length;i++) {   
   console.log(emps[i])   
}  
var newemps: string[] = new Array('test1','test2')   // accepts parameters separted by comma in Array object Constrcutor  

you can also see typescript array of object declaration

Array Destructing in typescript

[Destructing](/2018/08/es-6-features-destructuring-assignment.html) feature is introduced in the latest javascript. typescript also implemented in the object as well as arrays. Destructing code is more readable and reduces code size. Destructing is separating the elements of an array.

The below examples are to copy two variables without using third variables.

var var1 = 5, var2 = 8;  
console.log(var1, var2); // returned 5,8  
[var1, var2] = [var2, var1];  
console.log(var1, var2); // returned 8,5  

The same way we can implement in an array object.

  
var arrays:number[] =[7, 4,5];  
var [m,n] =arrays   
console.log(m, n); // 7, 4  

generated javascript using transpile is

  
var arrays = =[7, 4,5];  
var x = arrays[0], y = arrays[1];  
console.log(m, n); // 7, 4  

Array rest destructuring in typescript

We will see the array destructing with [rest operator](/2018/08/es6-spread-operator-in-javascript.html.

The above example has an array with three elements, assigned two variables, copied two values from an array to two variables, third will be ignored.

var arrays:number[] =[7, 4,5,12];  
var [m,n,...q] =arrays   
console.log(m, n); // 7, 4  
console.log(q); // 5,12  

We will see array ignore destructing.

  
var arrays:number[] =[7, 4,5,12];  
var [m,,...q] =arrays   
console.log(m); // 7  
console.log(q); // 5,12  

using an empty variable and leaving empty separated by the comma
Array Object Properties
length: returns the count of the elements in Array Object Array Object Methods
Array Object has different methods provided to manipulate an array of elements.

Method Description
reverse() Reverse order of elements in the array. The last element will be the first element, the First element will last element.
Push() takes one or more elements as parameters, add this element to the end of an array, and returns the new length of the array
pop() Delete an element from an array from the last position
concat() takes one or more elements as parameters, add this element to an original array and return the new array by concat this
slice() takes to start and end index, return the part of array elements
toString() outputs string form of array object
shift() delete the first element from an array index zero elements and returns the first element
unshift() takes one more element and these elements at the start of an array ie zero index position, return the completely new array elements

We will see real use cases of arrays with the example in the following section.

How to remove an element from an array?

using the splice method, we can remove the element from an array.

splice(0,1) - this elements remove the first element and return it.

the first parameter indicates were starting from an array i.e starting element. the second parameter indicates the number of elements to remove splice(arrays. length,1)these elements remove the last element and return the last element.

How to declare a multidimensional array?

These are used to two-level arrays of mathematical matrix objects. Multidimensional arrays are an array of values.

Arrays contain elements which elements hold arrays. Multidimensional arrays can be declared and initialized as follows.

  
var dimensions:number[][] = [[11,12,13],[3,2,5]]    
console.log(dimensions[0][0])  // returns 11  
console.log(dimensions[0][1])  // returns 12  
console.log(dimensions[0][2])  // returns 13  
console.log(dimensions[1][0])  // returns 3  
console.log(dimensions[1][1])  // returns 2  
console.log(dimensions[1][2])  // returns 5  

Using Index, we can retrieve elements like a normal array with multiple dimensional indexes.

How to Convert JSON to Array object in typescript.

In Applications, We used to get data from REST in the form of a JSON object. From the front end, we need to manipulate JSON objects and display them in the user interface. Convert JSON to arrays is the must-use case that the developer gets to know for efficient programming.

const json = {  
    "Employees": [  
        { "id": "1", "name": "john" },  
        { "id": "2", "name": "Franc" },  
        { "id": "3", "name": "Kiran" },  
  
    ]   
}  
  
const arraysItem = json.Employees.map(emp => emp.name);  
console.log(arraysItem); //return array with three elements -john,Franc,Kiran  

How to hold multiple data types values in the array.

Usually, arrays hold similar values of the same data type. We can also hold multiple data types like tuple array example.

An example for tuple types

  
var types1:[number, string] = [11, "cloudhadoop"]  
console.log(types1); //return index0 - 11, index1 - cloudhadoop  

How to Sort an array in typescript

Arrays. sort(comparator) method is used to sort the elements in an array

let list = ['11', '5', '9'];  
console.log(list) // return - return 11,5,9  
list.sort((p,q)=> p - q )  
console.log(list); // Ascending Order - return 5,9,11  
  
  
let data = [  
   {value:"testuser", key:11},  
   {value:"demo", key:31},  
   {value:"zoo", key:2},  
];  

Sorting JSON objects based on key and values and converting to Array

// sort value in natural ascending  order  
data.sort((d1, d2) => {  
  if (d1.value > d2.value) return 1;  
  if (d1.value < d2.value) return -1;  
  return 0;  
});  
console.log(data);  

output

{value: "demo", key: 31},  
{value: "testuser", key: 11},  
{value: "zoo", key: 2},  

here is an code for natural order

// sort key in natural ascending  order  
data.sort((d1, d2) => {  
  if (d1.key > d2.key) return 1;  
  if (d1.key < d2.key) return -1;  
  return 0;  
});  
  
{value: "zoo", key: 2},  
{value: "testuser", key: 11},  
{value: "demo", key: 31}  

How to Iterate/loop elements/objects in an array.

We can use [forEach](/2018/08/typescript-for-loop-tutorials-with.html) or normal for loop to iterate objects.

In the same logic, we can use loop object in an array

let list = ['11', '5', '9'];  
list.forEach( (element) => {  
    console.log(element)   
});  
  
//returns 11,5,9  

Conclusion

As a summary, you learned arrays in typescript with examples.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.