{

Learn Typescript Arrays Tutorial with Examples


Array Object introduction

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 list objects which are retrieved from the database, a list of JSON values, and custom entries as well as for storing primitive values. In typescripts arrays are objects. Elements from arrays can be retrieved by index.

Syntax

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

Array variable declaration and initialization

We can declare arrays and initialize them in many ways

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

and also using a single statement, we can declare and initialize arrays

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

the above holds values at index 0 - ‘one’, index 1- ‘two’, and index 2- ‘three’ we can also declare an array without datatype, which will treat as any datatype, arrays will assume that the data type of array can be decided based on values of the array we will see array example to check the type of an array, length of an array, retrieve an element from the 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  

Arrays Object Constructor example

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  

Array Destructing Basics

Destructing feature is introduced in the latest javascript. typescript is 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  

In the same way, we can implement it 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

We will see the array destructing with the rest operator. 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 the 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 the 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, adds 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, adds this element to an original array, and returns the new array by concat this

slice()

takes to start and end index, return the part of array elements

toString()

outputs string form of the 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 in 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) - these elements remove the first element and return it the first parameter indicates were starting from an array ie 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 for two-level arrays of mathematical matrix objects. Arrays contain elements which elements hold arrays. Multidimensional arrays can be declared and initialized as follows. Using Index, we can retrieve elements

  
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  

How to Convert JSON to Array object in typescript

In Applications, We used to get data from REST in the form of JSON objects. From the front end, we need to manipulate JSON objects and display them in the user interface. Converting JSON to arrays is 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

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

Sort an array example 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 keys 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},  
  
  
// 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}  

Iterate/loop elements/objects in a array

We can use forEach or normal for loop to iterate objects. In the same logic we can use a loop object in an array

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

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.