TypeScript Arrays

An array is a uniform set of elements of the same type that occupy consecutive memory addresses.

An array is a user-defined data type.

An array is a data structure that allows for the storage of elements that share the same data type. Within an array, only a predetermined number of elements can be stored. Additionally, it can also function as an object.

An array utilizes index-based storage, with the initial element located at index 0. The following structure aids in comprehending the organization of an array.

Characteristics of an Array

  • An array stores elements which have the same data type.
  • Array elements stored in contiguous memory locations.
  • The storage of 2-D array elements is rowed by row in a contiguous memory location.
  • Array name represents the address of the starting element.
  • The size of an array should be initialized at the declaration time.
  • Array size should be a constant expression and not a variable.
  • We can retrieve array elements by specifying the element's corresponding index value.
  • Advantage

Code Optimization: Utilizing an array contributes to enhancing code efficiency, which in turn boosts the program's speed and performance. It enables more effective retrieval and sorting of the array data.

Random access: This feature allows for the retrieval of any element within an array in constant time, irrespective of its position or the overall size of the array. Consequently, we can directly obtain any element located at a specified index.

Disadvantage

Size Restriction: An array permits the storage of a predetermined quantity of elements. After the array has been declared, its size cannot be modified. Therefore, if there is a need to add more elements than initially specified, it cannot be done.

Array declaration

Similar to JavaScript, TypeScript provides support for arrays as well. Arrays can be declared in two different ways:

  1. Utilizing square brackets.
  2. Example
    
    let array_name[:datatype] = [val1,val2,valn..]
    

Example:

Example

let fruits: string[] = ['Apple', 'Orange', 'Banana'];
  1. Using a generic array type.
  2. Example
    
    let array_name: Array<elementType> = [val1,val2,valn..]
    

Example:

Example

let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];

Types of the array in TypeScript

Arrays can be classified into two categories:

  • One-Dimensional Array
  • Multi-Dimensional Array
  • Single-Dimensional Array

A one-dimensional array is a form of linear array that consists of a single row for data storage. It utilizes one pair of square brackets (""). The elements can be accessed through either a row index or a column index.

Syntax

Example

let array_name[:datatype];

Initialization

Example

array_name = [val1,val2,valn..]

Example

Example

let arr:number[]; 
arr = [1, 2, 3, 4] 
console.log("Array[0]: " +arr[0]); 
console.log("Array[1]: " +arr[1]);

Output:

Output

Array[0]: 1
Array[1]: 2

Multi-Dimensional Array

A multi-dimensional array is defined as an array that includes one or more arrays within it. In such an array, data is organized using a row and column index, which is often referred to as matrix format. The most basic type of multi-dimensional array is the two-dimensional array (2-D array).

Syntax

Example

let arr_name:datatype[][] = [ [a1,a2,a3], [b1,b2,b3] ];

Initialization

Example

let arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1,val2,val 3], [v1,v2,v3]];

Example

Example

var mArray:number[][] = [[1,2,3],[5,6,7]] ;
console.log(mArray[0][0]);
console.log(mArray[0][1]);
console.log(mArray[0][2]);
console.log();
console.log(mArray[1][0]);
console.log(mArray[1][1]);
console.log(mArray[1][2]);

Output:

Output

1
2
3

5
6
7

Array Object

Array objects enable the storage of numerous values within a single variable. We can instantiate an array by utilizing the Array object. To create an array, the Array constructor accepts the following parameters:

  • A numerical value indicating the array's size or
  • A collection of values separated by commas.

Syntax

Example

let arr_name:datatype[] = new Array(values);

Example

Example

//array by using the Array object.
let arr:string[] = new Array("TypeScript Tutorial","2200","Java","Abhishek");
for(var i = 0;i<arr.length;i++) { 
   console.log(arr[i]);
}

Output:

Output

TypeScript Tutorial
2200
Java
Abhishek

Array Traversal by using a for...in loop

Example

Example

let i:any; 
let arr:string[] = ["TypeScript Tutorial", "2300", "Java", "Abhishek"];
for(i in arr) { 
   console.log(arr[i]) 
}

Output:

Output

TypeScript Tutorial
2300
Java
Abhishek

Passing Arrays to Functions

Arrays can be passed to functions by using the array name alone, omitting any index.

Example

Example

let arr:string[] = new Array("TypeScript Tutorial", "2300", "Java", "Abhishek"); 
//Passing arrays in function
function display(arr_values:string[]) {
   for(let i = 0;i<arr_values.length;i++) { 
      console.log(arr[i]);
   }  
}
//Calling arrays in function
display(arr);

Output:

Output

TypeScript Tutorial
2300
Java
Abhishek

TypeScript Spread operator

The spread operator facilitates the creation of arrays and objects by utilizing elements from an existing array or object. Additionally, it can be employed for object de-structuring. This feature is included in the ES 6 version.

Example

Example

let arr1 = [ 1, 2, 3];
let arr2 = [ 4, 5, 6];
//Create new array from existing array
let copyArray = [...arr1];   
console.log("CopiedArray: " +copyArray);
//Create new array from existing array with more elements
let newArray = [...arr1, 7, 8];
console.log("NewArray: " +newArray);
//Create array by merging two arrays
let mergedArray = [...arr1, ...arr2];
console.log("MergedArray: " +mergedArray);

Output:

Output

CopiedArray: 1,2,3
NewArray: 1,2,3,7,8
MergedArray: 1,2,3,4,5,6

Array Methods

The list of array methods with their description is given below.

SN Method Description
1. concat() It is used to joins two arrays and returns the combined result.
2. copyWithin() It copies a sequence of an element within the array.
3. every() It returns true if every element in the array satisfies the provided testing function.
4. fill() It fills an array with a static value from the specified start to end index.
5. indexOf() It returns the index of the matching element in the array, otherwise -1.
6. includes() It is used to check whether the array contains a certain element or not.
7. Join() It is used to joins all elements of an array into a string.
8. lastIndexOf() It returns the last index of an element in the array.
9. Pop() It is used to removes the last elements of the array.
10. Push() It is used to add new elements to the array.
11. reverse() It is used to reverse the order of an element in the array.
12. Shift() It is used to removes and returns the first element of an array.
13. slice() It returns the section fo an array in the new array.
14. sort() It is used to sort the elements of an array.
15. splice() It is used to add or remove the elements from an array.
16. toString() It returns the string representation of an array.
17. unshift() It is used to add one or more elements to the beginning of an array.

Input Required

This code uses input(). Please provide values below: