The Array type variable and object in TypeScript

An array is a special type of variable which is used to store multiple data sequentially. In an array, the type of data stored must be the same.

The limitation of variables can be solved by using an array.

  1. Variables are scaller in nature in that one variable contains only a single data at a time. SO while we needed a number of collection of data it’s not possible to use a variable.
  2. The variables are allocated memory in random order. So it’s not possible to get the values in order the variables are declared.

Features of array.

There are a numbers of features array provides us, and they are is as described below,

  1. An array allocates sequential memory blocks, thus we can find the data or values as it is in the array.
  2. The size of an array can not be changed after its initialization.
  3. Each memory block of the sequential allocated memory of an array represents an array element.
  4. The array element is identified by the array index or subscript.
  5. The array also has to declare before its use.
  6. The array elements can be updated and modified but can not be deleted.
  7. The data type of all elements of an array must be the same.

Declaration of an array.

to declare or initialize an array first take the keyword var then the name of the array and then the data type followed by a colon(:) and then the array symbol and then after the equal sign has to give the array elements separated by coma inside a square bracket.

Note: If not declared any datatype during initialization of an array, by default the type of the array will be of any type.

Example of an array Declaration:
var num_arr:number[] = [1,2,3,4,5];
console.log(num_arr);

How to access an array element

To access the array element we have to provide the name of the array and after that have to give the index of the element inside the square bracket.

Example of access of an array element:
var alpha_arr:string[] = ['abcd','efgh','ijkl','mnop'];
console.log(alpha_arr[0]);
console.log(alpha_arr[1]);
console.log(alpha_arr[2]);
console.log(alpha_arr[3]);

How to declare an array using Array Object

We also can create an array using an array object, for that first we have to declare a variable with its data type followed by a colon and after the data type, we have to give the array symbol. and then after the equal sign, we have to create the object by new Array() and inside the method, we have to pass the size of the array.
after the declaration of the array, we can insert the array elements using their index and for that, we have to type the property name of the array and then inside the square bracket have to pass the index of the element and then after equal sign have to provide the value of the element of the same data type.

Example of object type array:
var obj_arr:string[] = new Array(5);
obj_arr[0] = 'abcd';
obj_arr[1] = 'efgh';
obj_arr[2] = 'ijkl';
obj_arr[3] = 'mnop';
obj_arr[4] = 'qrst';
console.log(obj_arr);

Methods of array.

There is a list of the method we can use with an array object and the list and description of the method are given below with an example.

The methods are:

concat(): The concat method is used to get a new array with merge or concatenation of two or more arrays or values with an array.

Example of array concate:
var alpha_arr:string[] = ['abcd','efgh','ijkl'];
var num_arr:string[] = ['1','2','3'];
var alpha_num_arr = alpha_arr.concat(num_arr);

every(): The method is used to pass all the elements to a function and check if all the elements pass the test implemented. For that have to write the array property name then every method followed by a dot(.) and then inside the method we have to pass the name of the function which performs the checking.

Example of every method:
function isLessThan(arr_element,arr_index,arr){
	returns (arr_element <= 5);
}
var num_arr:number[] = [1,2,3,4,5,6,7,8,9];
var every_res = num_arr.every(isLessThan);
console.log(every_res);

filter(): The method filter is used to check and filter the elements which are not satisfied or return false by a checking function and creates a new array. To use the method we have to provide an array property name and then the method filter followed by a dot(.) and in the filter method, we have to pass the function name which is performing the checking.

Example of method filter
function isLessThan(arr_element,arr_index,arr){
	returns (arr_element <= 5);
}
var num_arr:number[] = [1,2,3,4,5,6,7,8,9];
var filter_res = num_arr.filter(isLessThan);
console.log(filter_res);

forEach(): The forEach method calls a function for each element of an array as a loop. To use the forEach method first have to provide the array property name then the forEach method is separated by a dot(.) and then they have to pass the function inside the forEach method.

Example of forEach method:
let num_arr:number[] = [1,2,3,4,5];
num_arr.forEach(function (val){
	console.log(val);
});

indexOf(): the index of the method returns the index of the element passed through the method. For that first right, the array property name and then indexOf method name are separated by a dot(.) and then inside the indexOf method have to pass the element value. If there are multiple same element values stored in the array then it will return the first index of the value passed through the method.

Example of method indexOf():
var num_arr:number[] = [12,13,14,15];
var arr_index = num_arr.indexOf(14); 
console.log("the array index is : " + arr_index );

join(): the method join is used to convert all the elements into a string, separated by a comma by default or you can pass a character through the join method by which you want to separate the array element. and for that first, you have to write the array property name and then join the method separated by dot(.) and then you can pass a character or string surrounded by a single or double quotation if you wish to separate the array element by the character or string

Example of join() method.
var char_arr:string[] = ['abcd','efgh','ijkl'];
var default_joint = char_arr.join();
console.log(default_joint);

var join_by_dash = chat_arr.join(' - ');
console.log(join_by_dash);

lastIndexOf(): The method lastIndexOf is used to get the last array index which is passed through the method.

Example of lastIndexOf():
let num_arr:number[] = [1,2,3,4,5,5,4,3];
var last_index = num_arr.lastIndexOf(5);
console.log('The last index of 5 is: ' + last_index);

map(): The method map is used to get a new array with the same type of modification with all elements of an array. For that write the array property name and then the map method separated by a dot(.) and then pass the function through the method.

Example of map():
let num_arr:number[] = [2,4,16];
let sqrt_arr = num_arr.map(Math.sqrt);
console.log(sqrt_arr);

pop(): The method returns an array, removing the last element of an array.

Example of pop();
let num_arr:number[] = [1,3,5,7,9];
let poped_arr = num_arr.pop();
console.log(poped_arr);

push(): The method push entered one or multiple elements in an array and returns the modified array. To write that first write the array property name then the method push() separated by a dot (.) and then pass the value you want to push through the method.

Example of array push():
let num_arr:number[] = [1,3,5,7];
let pushed_arr = num_arr.push(9);
console.log(pushed_arr);

reduce(): the reduce method is simultaneously applied to an array from the left to right and passes through a function until or unless it becomes a single element. for that write an array property name and then reduce method separated by a dot and through the reduce method pass the function to do a particular job with two-element and convert into one element.

Example of reduce function:
let num_arr:number[] = [0,1,2,3];
var arr_total = num_arr.reduce(function(x,y){ return x+y; });
console.log(arr_total);

reduceRight(): like reduce method reduceRight method is also simultaneously applied to an array and returns a single element but in this case, the flow is done from right to left. for that write an array property name and then the reduceRight method separated by a dot() and through the reduceRight method pass the function to do a particular job with two-element and convert into one element.

Example of reduceRight():
let num_arr:number[] = [0,1,2,3];
var arr_total = num_arr.reduceRight(function(x,y){ return x+y; });
console.log(arr_total);

reverse(): The method reverse() is used to make an array in the reverse order that is the first element will be the last element and the last one will become the first one. And to apply reverse you have to first right the property name of an array and then reverse method followed by a dot(.)

Example of reverse():
var alpha_arr:string[] = ['aa','bb','cc','dd'];
var rev_arr = alpha_arr.reverse();
console.log(rev_arr);

shift(): The shift() method removes the first element from an array and returns the removed element. And to apply that in an array write the property name of an array and then shift method separated by a dot symbol.

Example of shift():
var num_arr:number[] = [10,20,30,40,50];
var shifted_num = num_arr.shift();
console.log(shifted_num);

slice(): The slice() method extracts an array from an array between 2 indexes but not including the second index element and returns an array. To apply slice() take an array and right and slice method separated by a dot(.), and pass two index points through the slice method.

Example of Slice Method:
var num_arr:number[] = [10,20,30,40,50];
var sliced_arr = num_arr.slice(1, 3);
console.log(sliced_arr);

some(): the some() method is used to test an array if there is at least one array element that can satisfy a condition declared inside a function. Na to do that first declare an array and right the method with the array separated by a dot symbol and then pass a function through the same method.

Examples of some methods:
function isLessThan(arr_element, arr_index, arr){
	return (arr_element<=5);
}
let num_arr:number[] = [2,4,6,8];
var some_res = num_arr.some(isLessThan);
console.log(some_res);

sort(): The sort() method is used to short the elements of an array and return a new array. And to apply the sort() method with an array you have to declare an array and have to attach the sort() method with the array separated by a dot.

Example of sort():
var alpha_arr:string[] = ['a','c','d','b'];
var shorted_arr = alpha_arr.short();

splice(): the method splice() is adding an element in a particular index position and can remove some old element simultenusly. To apply the splice() method first declare an array and attach the method splice() with it separated by a dot symbol, and then pass the parameters through the method, you can pass 3 parameters through the splice() method, the first parameter denotes the index of element, the second one denotes how many elements need to remove from the index position towards the right, and then the last one denotes the element to insert in the index position.

Example of splice():
var alpha_arr:string[] = ['a','c','d','b'];
var removed_element = alpha_arr.splice(2,1,'m');
console.log('Current array : ' + alpha_arr);
console.log('The removed element is: ' + removed_element);

toString(): the method toString() converts an array to a string with all elements of the array separated by a comma and returns it. To apply the toString() method declare an array and attach the method toString() with it separated by a dot (.),

Example of toString():
var alpha_arr:string[] = ['a','c','d','b'];
var string_converted_arr = alpha_arr.toString();
console.log(string_converted_arr);

unshift(): the method unshift() is used to add an element at the beginning of an array and returns the element added to the array. To use unshift() method first declare an array and apply the method unshift() with the array separated by a dot (.) and then pass the element value through the unshift() method.

Example of unshift():
var alpha_arr:string[] = ['a','c','d','b'];
var unshift_arr = alpha_arr.unshift('m');
console.log(unshift_arr);

Destructuring an array

to break an array into some variables we are using the destructuring process. it is used to assign the value to some variables.

Examples of Destructuring:
var num_arr:number[] = [10,12];
var[a,b] = num_arr;
console.log(a);
console.log(b); 

Ger the element of an array by for loop:

We can get all the elements through a loop and we can use for loop to get the array elements. For that, we have to declare an array and then inside for loop first have to take a variable which will store each element and then in a keyword and then the array property name.

Example of taking array elements in a for loop:
var j:any;
let num_arr:number[] = [1,2,3,4,5];
for(j in num_arr){
	console.log(j);
}

The concepts of the array in typescript:

TypeScript supports many concepts and they are described below:

Multi Dimantional Array:

An array element value contains another array and it may go in a tree structure, Such kind of array is called a multi-dimensional array. The simple form of the multi-dimensional array is a two-dimensional array.

Example of the two-dimensional array:
let multi_dimantional_num_arr:number[][] = [[10,20,30],[40,50,60,70]];  
console.log(multi_dimantional_num_arr[0][0]);
console.log(multi_dimantional_num_arr[0][1]); 
console.log(multi_dimantional_num_arr[0][2]); 
console.log(multi_dimantional_num_arr[1][0]); 
console.log(multi_dimantional_num_arr[1][1]); 
console.log(multi_dimantional_num_arr[1][2]);
console.log(multi_dimantional_num_arr[1][3]);

Pass an array through functions

An array name only can be passed through a function without passing any index.

Example of passing an array through a function
var alpha_arr:string[] = ['aa','bb','cc','dd'];  

function display_alpha(arr_names_alpha:string[]) {
   for(var i = 0;i<arr_names_alpha.length;i++) { 
      console.log(arr_names_alpha[i]) ;
   }  
}  
display_alpha(alpha_arr);

Return an array from a function:

you can return a full array from a function and display it outside the function

Example of return an array from a function
function display_alpha():string[] {
	let arr_names_alpha:string[] = ['aa','bb','cc','dd']; 
	return arr_names_alpha;
}
var alpha_arr:string[] = display_alpha();
for(var i = 0;i<alpha_arr.length;i++) { 
  console.log(alpha_arr[i]) ;
}

Share The Post On -

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.