Monday, July 23, 2018

Learn Typescript Arrays Tutorial with Examples

Array Object introduction

Arrays are basics of any language. Arrays is used to store the multiple values under a one collection name. Basically, in a web application, we will use Arrays for storing list objects which are retrieved from the database, 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 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 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', index 2- 'three' we can also declare array without datatype, will treat as any datatype, arrays will assume that data type of array can be decided based on values of array we will see array example to check typeof of an array, length of an array, retrieve element from 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 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 We will see the array destructing with 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 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 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 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 in the start of an array ie zero index position, return the complete 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 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 where starting from an array ie starting element
second parameter indicates the number of elements to remove splice(arrays.length,1) - these elements removes 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. 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 JSON object. From the front end, we need to manipulate JSON object and display in the user interface. Conver JSON to arrays is must use case that 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 key and values and convert 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. 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