TypeScript Array

In TypeScript, arrays are used to store collections of elements of the same datatype. TypeScript arrays are dynamic i.e. they can grow or shrink in size dynamically during runtime. Unlike some statically typed languages, such as Java, where arrays have fixed sizes determined at compile time, TypeScript arrays can be modified by adding or removing elements at runtime.

In this Typescript tutorial, we will learn to create an array, clone an array, merge arrays, and iterate through the elements of an array in TypeScript with easy-to-follow examples.

TypeScript does not have a seperate built-in type for List. TypeScript arrays can resize dynamically, so the arrays are used as lists.

1. Creating an Array

Like JavaScript, TypeScript has an Array type to allow the assignment of multiple values. The array is specified by adding a square bracket [] after the type.

To use the type-safety capability of TypeScript, we can add diamond brackets to specify the type of elements in the array. Every time a new value is added to such a generic array, the compiler checks for type compatibility and alerts if there is a type mismatch. The following example declares a boolean array and then initializes its values.

//Various ways to declare a typed array
let myArr1: boolean[];
let myArr2: boolean[] = [];
let myArr3: boolean[] = new Array();
let myArr4: boolean[] = Array();

//Initializing an array
myArr1 = [false, false, true];

We can declare and initialize the array with values in the same line.

let flags: boolean[] = [false, false, true];	
//or
let flags: Array<boolean> = [false, false, true];

2. Add, Retrieve and Delete Values from Array

We can use the following methods to add and remove elements from arrays:

Array MethodDescription
push()Adds one or more elements to the end of an array and returns the new length of the array.
pop()Removes the last element from an array and returns that element.
unshift()Adds one or more elements to the beginning of an array and returns the new length of the array.
shift()Removes the first element from an array and returns that element.
splice()Adds or removes elements from an array.
slice()Returns a shallow copy of a portion of an array into a new array object.
let fruits: string[] = ['apple', 'banana', 'orange'];

// Adds an Item
fruits.push('grape');  //['apple', 'banana', 'orange', 'grape']

// Removes the last element ('grape') from the array
let removedFruit = fruits.pop();  // ['apple', 'banana', 'orange']

// Adds 'pear' to the beginning of the array
fruits.unshift('pear');  //  ['pear', 'apple', 'banana', 'orange']

// Removes the first element ('pear') from the array
let removedFruit2 = fruits.shift();  //['apple', 'banana', 'orange']

// Removes 'banana' from the array
fruits.splice(1, 1);  // ['apple', 'orange']

// Creates a shallow copy of a portion of the array
let slicedArray = fruits.slice(0, 1);
console.log(slicedArray); // Output: ['apple']

See Also: Different ways to add items to Array and remove items from Array

3. Iterating over an Array

We can use either of for loops to iterate over array elements.

3.1. Using for…of Loop

let scores :number[] = [10, 20, 30, 40];	

for (var score of scores) {
	console.log(score);		//Outputs 10 20 30 40
}

DO NOT use “for…in” loop which is used to iterate over object attributes.

3.2. Using Traditional for Loop

let scores :number[] = [10, 20, 30, 40];	

for (var i = 0; i &lt; scores.length; i++) {
	console.log(scores[i]);		//Outputs 10 20 30 40
}

4. Cloning an Array

Use the spread operator to clone the array. It is the easiest and the most recommended way.

let origScores: number[] = [10, 20, 30];	

let clonedScores: number[] = [...origScores];

console.log(clonedScores);		//[10, 20, 30]

origScores.push( 40 );

console.log(origScores);		//[10, 20, 30, 40] is "changed"
console.log(clonedScores);		//[10, 20, 30] 	is "unchanged"

5. Merging Two Arrays

Use the spread operator for merging arrays as well. It’s the simplest and most recommended way.

let scores1: number[] = [10, 20, 30];
let scores2: number[] = [40, 50, 60];	

let mergedScore = [...scores1, ...scores2];

console.log(mergedScore);	//[ 10, 20, 30, 40, 50, 60 ]

Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode