You are currently viewing TypeScript Arrays: A Comprehensive Guide with Examples

TypeScript Arrays: A Comprehensive Guide with Examples

Arrays are fundamental data structures in TypeScript that allow you to store and manipulate collections of items. In this tutorial, you’ll explore how to work with arrays in TypeScript, covering array declaration, initialization, manipulation, and common array operations.

Declaring Arrays in TypeScript

You can declare arrays in TypeScript using two syntaxes:

  1. Using square brackets notation:
   let numbers: number[];
  1. Using Array generic type:
   let names: Array<string>;

Initializing Arrays

Arrays in TypeScript can be initialized using various methods:

Initializing with Values

let numbers: number[] = [1, 2, 3, 4, 5];

Initializing with Array Constructor

let names: Array<string> = new Array("John", "Doe", "Jane");

Accessing Array Elements

You can access array elements using square bracket notation with the index:

let fruits: string[] = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Output: Apple

Modifying Arrays

Adding Elements

let colors: string[] = ["Red", "Blue"];
colors.push("Green"); // Adds "Green" to the end of the array

Removing Elements

let numbers: number[] = [1, 2, 3, 4, 5];
numbers.pop(); // Removes the last element from the array

Iterating through Arrays

Using for…of Loop

let fruits: string[] = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
    console.log(fruit);
}

Using forEach Method

let numbers: number[] = [1, 2, 3, 4, 5];
numbers.forEach(function (num) {
    console.log(num);
});

Common Array Operations

Finding Elements

let numbers: number[] = [1, 2, 3, 4, 5];
let found = numbers.find(num => num === 3); // Output: 3

Filtering Elements

let numbers: number[] = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0); // Output: [2, 4]

Mapping Elements

let numbers: number[] = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(num => num * num); // Output: [1, 4, 9, 16, 25]

Conclusion

Arrays are versatile data structures in TypeScript that enable you to store and manipulate collections of items efficiently. By understanding array declaration, initialization, manipulation, and common operations, you can effectively work with arrays in TypeScript for various programming tasks.

Leave a Reply