Open In App

TypeScript Arrays

Last Updated : 02 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

An array is a user-defined data type. An array is a homogeneous collection of similar types of elements that have a contiguous memory location and which can store multiple values of different data types.

An array is a type of data structure that stores the elements of a similar data type and considers it as an object too. We can store only a fixed set of elements and can’t expand its size, once its size is declared.

The array follows index-based storage i.e. the first element of an array is stored at index 0 or index ‘i’ and the remaining elements are stored at the location ‘i+1’.

Features of an Array 

  • The same data type of elements is stored in an array.
  • Array elements are always stored in contiguous memory locations.
  • Storage of 2-D array elements is rowed by row in a contiguous memory location.
  • The Starting element of the address is represented by the array name.
  • The size of an array should be declared at the time of initialization.
  • The remaining elements of an array can be retrieved by using the starting index of an Array.

Typescript supports an array just like that in JavaScript. There are two ways to declare an array in typescript:

1. Using square brackets. 

let array_name[:datatype] = [val1, val2, valn..]  

Example: 

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

2. Using a generic array type. 
TypeScript array can contain elements of different data types, as shown below. 

let array_name: Array = [val1, val2, valn..]  

Example: Multi Type Array 

let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; 
// or 
let values: Array = ['Apple', 2, 'Orange', 3, 4, 'Banana']; 

Example: Access Array Elements 

  • Array elements access on the basis of index i.e.)ArrayName[index].
let fruits: string[] = ['Apple', 'Orange', 'Banana']; 
fruits[0]; // returns Apple
fruits[1]; // returns Orange
fruits[2]; // returns Banana
fruits[3]; // returns undefined
  • We can access the array elements by using the ‘FOR’ loop:
let fruits: string[] = ['Apple', 'Orange', 'Banana'];

for (let index in fruits) {
    console.log(fruits[index]);  // output: Apple Orange Banana
}

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]); // output: Apple Orange Banana
}

Advantages 

  • Code Optimization: We can retrieve or sort the array data more efficiently. 
  • Random access: We can randomly access the array data using the location pointer.

Disadvantages 

  • Size Limit: The size of an Array is fixed i.e.)static. We cannot increase the array size once it has been declared.

There are two types of an array:

  • Single-Dimensional Array 
  • Multi-Dimensional Array 

Single-Dimensional Array: It is the simplest form of an array that contains only one row for storing data. It contains single set of the square bracket (“[]”). 

Syntax: 

let array_name[:datatype]; 

Initialization: 

array_name = [val1, val2, valn..]

Example:

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

Output: 

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

Multi-Dimensional Array 

The data is stored in rows and columns (also known as matrix form) in a Multi-dimensional array.

Syntax: 

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

Initialization: 

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

Example:

let mArray:number[][] = [[10, 20, 30], [50, 60, 70]] ;  
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: 

10
20
30
50
60
70

Array Object

We can create an Array by using or initializing the Array Object. The Array constructor is used to pass the following arguments to create an Array: 

  • With the numeric value which represents the size of an array.
  • A list of comma separated values.

Syntax: 

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

Example: 

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

Output: 

GEEKSFORGEEKS
2200
Java
Abhishek

Passing an Array to a Function

We can pass an Array to a function by specifying the Array name without an index. 

Example: 

let arr:string[] = new Array("GEEKSFORGEEKS", "2300", "Java", "Abhishek");   

// Passing an Array in a function  
function display(arr_values:string[]) {  
   for(let i = 0;i<arr_values.length;i++) {   
      console.log(arr[i]);  
   }    
}  

// Calling an Array in a function  
display(arr);

Output 

GEEKSFORGEEKS
2300
Java
Abhishek


Using TypeScript ‘Spread’ operator

The spread operator can be used to initialize arrays and objects from another array or object. It can also be used for object destructuring. It is a part of ECMAScript 6 version.

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:

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

TypeScript Arrays – FAQs

How to add elements to an array in TypeScript?

You can add elements using methods like push() (array.push(element);), unshift() for adding to the start, or using the spread operator (array = […array, element];).

How to iterate over an array in TypeScript?

You can iterate over an array using loops like for, for…of, or higher-order functions like forEach(), map(), and filter().

How to find the length of an array in TypeScript?

Use the length property to find the number of elements in an array: let length = array.length;.

How to remove elements from an array in TypeScript?

Elements can be removed using methods like pop() (removes the last element), shift() (removes the first element), or splice(index, count) (removes elements at a specific position).

How to check if an element exists in an array in TypeScript?

Use methods like includes(element), indexOf(element) !== -1, or some(callback) to check if an element exists in an array.



Next Article

Similar Reads

three90RightbarBannerImg