TypeScript

8.Understanding Arrays in TypeScript

Understanding Arrays in TypeScript

Arrays are one of the most commonly used data structures in programming. In TypeScript, arrays provide a way to store multiple values in a single variable, where each value can be accessed via its index. The elements in an array can be of the same data type, making them an essential part of organizing and managing data.

In this blog post, we will explore TypeScript arrays, their syntax, usage, and some useful methods that allow you to manipulate them. Whether you’re just starting with TypeScript or looking to expand your knowledge, this guide will help you get a better understanding of arrays and how they work in TypeScript.


What is an Array?

An array is a collection of elements that share a common name, and each element is accessed using an index. In TypeScript, arrays are a user-defined data type that allows you to store multiple values of the same type under one variable. The index of an array always starts from 0, meaning that the first element in the array has an index of 0, the second element has an index of 1, and so on.

Syntax for Declaring Arrays

In TypeScript, arrays can be declared and initialized in a variety of ways. The most common way to declare an array is by using the following syntax:

Declaring an Array

// Declaration
var colors: string[];

// Initialization
colors = ['red', 'blue', 'green', 'yellow'];

In the above example:

  • string[] specifies that the array will hold values of the type string.

  • colors = ['red', 'blue', 'green', 'yellow']; initializes the array with four color values.

You can also declare an array without specifying the data type, in which case TypeScript will consider the array to hold values of any data type (any).

Example:

var colors: string[] = ['red', 'blue', 'green', 'yellow'];

Accessing Array Elements

To access an element in an array, you can use the array name followed by the index of the element inside square brackets [].

Example:

console.log(colors[0]); // Output: 'red'

Since arrays are 0-indexed, colors[0] refers to the first element in the array, which is 'red'.

You can also loop through arrays using a for loop or for...of loop to access each element.

Example:

// Using a for loop
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}

// Using a for...of loop
for (let color of colors) {
console.log(color);
}

Array as an Object

TypeScript also allows you to create arrays using the Array constructor. Inside the constructor, you can either pass a numeric value (to specify the length of the array) or provide a comma-separated list of values.

Example:

// Using numeric data in Array constructor
var list: number[] = new Array(10);
for (var i = 0; i < list.length; i++) {
list[i] = i * 2;
console.log(list[i]); // Output: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18
}

// Using string values in Array constructor
var courses: string[] = new Array('Java', 'Mean Stack', 'PHP', 'JSP');
for (var i = 0; i < courses.length; i++) {
console.log(courses[i]); // Output: 'Java', 'Mean Stack', 'PHP', 'JSP'
}

Array Methods

TypeScript provides various built-in methods to manipulate and work with arrays. Below are some of the most commonly used array methods:

  1. concat(): Combines two or more arrays and returns a new array.

var alpha = ['a', 'b', 'c'];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Output: ['a', 'b', 'c', 1, 2, 3]
  1. filter(): Creates a new array with elements that satisfy the provided condition.

function isBigEnough(element: number) {
return element >= 10;
}

var passed = [12, 5, 8, 130, 44].filter(isBigEnough);
console.log(passed); // Output: [12, 130, 44]

  1. forEach(): Executes a provided function once for each array element.

let num = [7, 8, 9];
num.forEach(function (value) {
console.log(value); // Output: 7, 8, 9
});
  1. indexOf(): Returns the first index of an element, or -1 if not found.

var index = [12, 5, 8, 130, 44].indexOf(8);
console.log(index); // Output: 2
  1. join(): Joins all elements of an array into a string.

var arr = new Array('First', 'Second', 'Third');
console.log(arr.join()); // Output: 'First,Second,Third'
console.log(arr.join(', ')); // Output: 'First, Second, Third'
  1. map(): Creates a new array with the results of calling a provided function on every element.

var numbers = [1, 2, 3, 4];
var doubled = numbers.map(function (num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]
  1. pop(): Removes the last element from an array and returns that element.

var colors = ['red', 'blue', 'green'];
var lastColor = colors.pop();
console.log(lastColor); // Output: 'green'
console.log(colors); // Output: ['red', 'blue']
  1. push(): Adds one or more elements to the end of an array and returns the new length.

var colors = ['red', 'blue'];
colors.push('green');
console.log(colors); // Output: ['red', 'blue', 'green']
  1. reduce(): Applies a function to reduce the array to a single value.

var numbers = [1, 2, 3, 4];
var sum = numbers.reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
});
console.log(sum); // Output: 10
  1. reverse(): Reverses the order of elements in the array.

var numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]

Array Destructuring

Array destructuring allows you to unpack values from arrays into distinct variables. This can make your code cleaner and more readable.

Example:

let list: number[] = [200, 400, 600];
let [a, b, c] = list;
console.log(a); // Output: 200
console.log(b); // Output: 400
console.log(c); // Output: 600

Array Looping with for...in Loop

The for...in loop can be used to loop through the indexes of the array elements.

Example:

var list: number[] = [100, 200, 300, 400];

for (let i in list) {
console.log(list[i]);
}

This loop performs index-based traversal and outputs:

  • 100

  • 200

  • 300

  • 400


Conclusion

Arrays are an essential part of TypeScript that allow developers to store and manipulate collections of values efficiently. In this blog post, we covered:

  • Array Declaration: How to declare and initialize arrays.

  • Accessing Array Elements: Using indexes and loops to retrieve elements.

  • Array Methods: A variety of built-in methods to manipulate arrays.

  • Array Destructuring: An elegant way to extract array values.

  • Looping with for...in: How to traverse arrays using a for...in loop.

With this knowledge, you can work with arrays in TypeScript confidently and apply these techniques in your projects.

Leave a Reply

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