TypeScript Arrays

Placement-ready Online Courses: Your Passport to Excellence - Start Now

In TypeScript, arrays store a group of identically sized elements. They are introduced using the notation of square brackets. They can be filled later using various techniques or initialized with values upon declaration.

TypeScript provides built-in support for arrays, including methods for adding, removing, and manipulating elements within an array. Additionally, arrays can be used in conjunction with various control structures, such as loops, to perform complex operations on the collection of elements they contain.

TypeScript also supports using multi-dimensional arrays, which allow storing elements in multiple dimensions, such as rows and columns. Multi-dimensional arrays are declared using nested square brackets notation.

Arrays in TypeScript can have a fixed length or a dynamic length, and the length of an array can be obtained using the length property. Finally, TypeScript also supports using array types, which allow developers to specify the data type of the elements contained in the array.

Defining Arrays in TypeScript

To define an array in TypeScript, you can use the following syntax:

let DataFlair_myArray: Array<type> = [element1, element2, ..., elementn];

The element1, element2, etc. parameters provide the starting elements of the array, and the type parameter indicates the type of items the array will contain. You can use the following code, for instance, to define an array of strings with the components “apple,” “banana,” and “cherry”:

let DataFlair_fruits: Array<string> = ['apple', 'banana', 'cherry'];

Alternatively, you can use the following syntax to define an array:

let DataFlair_myArray: type[] = [element1, element2, ..., elementn];

This syntax is equivalent to the previous one but is more concise. For example, to define the same array of strings, you can use the following code:

let DataFlair_fruits: string[] = ['apple', 'banana', 'cherry'];

Initializing Arrays in TypeScript

In TypeScript, you can initialize an array in several ways, including:

1. a fixed number of elements

2. variable number of elements

3. default value for each element

To initialize an array with a fixed number of elements, you can use the Array constructor as follows:

let DataFlair_myArray = new Array(n);

The n parameter specifies the number of elements that the array will contain. For example, to create an array of five numbers, you can use the following code:

let DataFlair_numbers = new Array(5);

This will create an array with five undefined elements. To set the value of an element in the array, you can use the index operator as follows:

DataFlair_numbers[0] = 1;
DataFlair_numbers[1] = 2;
DataFlair_numbers[2] = 3;
DataFlair_numbers[3] = 4;
DataFlair_numbers[4] = 5;

Alternatively, you can initialize an array with a fixed number of elements using the array syntax as follows:

let DataFlair_myArray: type[] = new Array<type>(n);

For example, to create an array of five strings, you can use the following code:

let DataFlair_fruits: string[] = new Array<string>(5);

This will create an array with five undefined strings. To set the value of an element in the array, you can use the index operator as follows:

DataFlair_fruits[0] = 'apple';
DataFlair_fruits[1] = 'banana';
DataFlair_fruits[2] = 'cherry';
DataFlair_fruits[3] = 'orange';
DataFlair_fruits[4] = 'pear';

Initializing an Array with a Variable Number of Elements

To initialize an array with a variable number of elements, you can use the array syntax as follows:

let DataFlair_myArray: type[] = [element1, element2, ..., elementn];

For example, to create an array of strings containing the elements “apple,” “banana,” and “cherry,” you can use the following code:

let DataFlair_fruits: string[] = ['apple', 'banana', 'cherry'];

This syntax is convenient when you know the initial elements of the array at the time of declaration.

Initializing an Array with a Default Value for Each Element

You can use the array’s “fill” method to initialize an array with a default value for each element, as seen below:

let DataFlair_myArray = new Array(n).fill(value);

The `n` parameter specifies the array’s number of elements, and the `value` parameter specifies the default value for each element. For example, to create an array of five numbers with the value 0 for each element, you can use the following code:

let DataFlair_numbers = new Array(5).fill(0);

This will create an array with five elements, each with the value 0.

Accessing and Manipulating Arrays in TypeScript

Once you have defined and initialized an array in TypeScript, you can access and manipulate its elements using various methods and properties.

Accessing Array Elements

To access an element of an array in TypeScript, you can use the index operator as follows:

let DataFlair_element = myArray[index];

The `index` parameter specifies the zero-based index of the element you want to access, and the `DataFlair_element` variable will contain the element’s value.

For example, to access the second element of an array of numbers, you can use the following code:

let DataFlair_numbers = [1, 2, 3, 4, 5];
let secondNumber = DataFlair_numbers[1]; // secondNumber = 2

Manipulating Array Elements

To manipulate the elements of an array in TypeScript, you can use various methods and properties.

Adding Elements to an Array

The array’s “push” method in TypeScript can be used to add an element to the end of an array, as shown below:

DataFlair_myArray.push(element);

The `element` parameter specifies the element’s value you want to add.

For example, to add the number 6 to the end of an array of numbers, you can use the following code:

let DataFlair_numbers = [1, 2, 3, 4, 5];
DataFlair_numbers.push(6);

This will add 6 to the end of the `DataFlair_numbers` array.

Removing Elements from an Array

With TypeScript’s splice method, you can eliminate an element from an array as seen below:

DataFlair_myArray.splice(index, count);

The `index` parameter specifies the zero-based index of the element you want to remove, and the `count` parameter sets the number of elements you want to remove.

For example, to remove the second and third elements of an array of numbers, you can use the following code:

let DataFlair_numbers = [1, 2, 3, 4, 5];
DataFlair_numbers.splice(1, 2);

This will remove the elements with the values 2 and 3 from the `numbers` array.

Updating Array Elements

To update an element of an array in TypeScript, you can use the index operator as follows:

DataFlair_myArray[index] = element;

The `index` parameter specifies the zero-based index of the element you want to update, and the `element` parameter sets the new value of the element.

For example, to update the third element of an array of numbers to the value 7, you can use the following code:

let DataFlair_numbers = [1, 2, 3, 4, 5];
DataFlair_numbers[2] = 7;

This will update the third element of the `DataFlair_numbers` array to the value 7.

Iterating Over an Array

You can use various looping constructs. The for loop or the array’s forEach method, to repeatedly iterate over the items of an array in TypeScript.

For instance, you can use the following code to print the components of a number array to the console:

let DataFlair_numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < DataFlair_numbers.length; i++) {
 console.log(DataFlair_numbers[i]);
}

Output

1
2
3
4
5

This will print the elements of the numbers array to the console.

Alternatively, you can use the forEach method of the array to iterate over its elements, as follows:

let DataFlair_numbers = [1, 2, 3, 4, 5];
DataFlair_numbers.forEach(function (element) {
 console.log(element);
});

Output

1
2
3
4
5

This will also print the elements of the numbers array to the console.

Working with Multidimensional Arrays in TypeScript

In TypeScript, you can define multidimensional arrays by nesting one or more arrays inside another array.

For example, to define a two-dimensional array of numbers, you can use the following code:

let DataFlair_matrix = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9],
];

This will create a two-dimensional array with three rows and three columns.

With TypeScript, you can use the index operator for each dimension to access a specific element in a multidimensional array as seen below:

let DataFlair_element = DataFlair_myArray[rowIndex][columnIndex];

In addition to setting the zero-based index of the column containing the element, the rowIndex and columnIndex parameters also specify the zero-based index.

For example, to access the element in the second row and third column of a two-dimensional array of numbers, you can use the following code:

let DataFlair_matrix = [
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9],
];
let element = DataFlair_matrix[1][2]; // element = 6

Output

6

This will access the element with the value 6.

Readonly

In TypeScript, the Readonly modifier can be applied to an array to prevent its elements from being modified after initialization. This means that once an array is declared as readonly, its elements cannot be added, removed, or updated.

This is useful in situations where you want to ensure that the contents of an array remain constant throughout the program’s execution, such as when using an array as a constant lookup table or when sharing an array between multiple parts of your program.

To make an array readonly in TypeScript, you can use the ReadonlyArray<T> type. For example, to declare a readonly array of strings, you can use the following syntax:

const DataFlair_myArray: ReadonlyArray<string> = ['foo', 'bar', 'baz'];

Once this array is initialized, its elements cannot be modified. If you attempt to modify the array, TypeScript will generate a compile-time error.

DataFlair_myArray[0] = 'qux'; // Error: Index signature in type 'readonly string[]' only permits reading.
DataFlair_myArray.push('qux'); // Error: Property 'push' does not exist on type 'readonly string[]'.

Overall, Readonly arrays provide an additional layer of type safety in TypeScript, helping to catch potential errors at compile-time rather than at runtime.

Features of array, array object, array methods

Arrays are an important data structure in TypeScript, and they offer many useful features, such as:

1. Storing collections of elements: Arrays allow storing multiple elements of the same data type in a single variable.

2. Indexed access: You can access individual elements within an array by their index, which starts at zero.

3. Dynamic resizing: You can add or remove elements from an array dynamically, meaning an array’s size can change during runtime.

4. Iteration: You can use loops to iterate over the elements in an array and perform operations on them.

In addition to these basic features, TypeScript also provides several built-in methods for working with arrays. Some of the most commonly used array methods include:

  • push(): Adds an element to the end of the array.
  • pop(): Removes and returns the last element in the array.
  • shift(): Removes and returns the first element in the array.
  • unshift(): Adds an element to the beginning of the array.
  • splice(): Removes or replaces elements in an array.
  • slice(): Returns a new array containing a subset of the original array.
  • concat(): Joins two or more arrays together to create a new array.

These methods, along with other features of arrays in TypeScript, make them a powerful tool for working with data collections in various applications.

Spread Operator in TypeScript

The spread operator in TypeScript is a syntax that allows you to expand an iterable (such as an array or a string) into multiple elements. It is denoted by the ellipsis (…) and can be used in various contexts, including function calls, array literals, and object literals.

One of the most common use cases for the spread operator in TypeScript is to concatenate two or more arrays. For example, you can use the spread operator to concatenate two arrays as follows:

const DataFlair_arr1 = [1, 2, 3];
const DataFlair_arr2 = [4, 5, 6];
const concatenatedArray = [...DataFlair_arr1, ...DataFlair_arr2];
console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]

Output

[1,2,3,4,5,6]

Another use case for the spread operator is to pass an array as individual arguments to a function. For example, suppose you have a function that takes three arguments like this:

function DataFlair_myFunction(arg1: number, arg2: number, arg3: number) {
 console.log(arg1, arg2, arg3);
}

You can use the spread operator to pass an array of three numbers as arguments to this function:

const myArgs = [1, 2, 3];
DataFlair_myFunction(...myArgs); // Output: 1 2 3

A spread operator is a powerful tool in TypeScript that allows you to work with arrays and other iterables concisely and expressively. Using the spread operator, you can simplify your code and make it more readable and maintainable.

Conclusion

Arrays are a crucial data structure in TypeScript that makes it possible to store and manage collections of values effectively. You may initialize arrays, access and modify array elements, iterate over arrays, and utilize various other TypeScript properties. You may use arrays to address various programming issues and produce robust programs by learning these methods.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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