Array in TypeScript

Learn via video courses
Topics Covered

Overview

Types in a programming language are related to the type of information that a certain program holds. Depending on its substance, information or data may be divided into many kinds. Data types are typically embedded into programming languages, Array data type is a part of Structural data types

Introduction to TypeScript Arrays

Variables have a scalar character. To put it another way, a variable declaration can only include one variable at a time. This indicates that n variable declarations will be required to store n values in a program. As a result, the usage of variables is not viable for storing a bigger collection of values.

Variables in a program are assigned memory in a random sequence, making it impossible to retrieve/read the values in the order in which they were declared.

To address this, TypeScript provides the idea of arrays. An array is a set of values that are all the same. An array is just a collection of items of the same data type. It is a kind that has been defined by the user. Now first let’s see what User defined/ Structured types are?

Only one value can be stored at a time in a simple data type. Each data item in a structured data type is a collection of other data items. A structured data type utilizes a single identifier for the whole collection (name). Structured data types are used to aggregate similar data of different types for easy access using a single identifier. Data may then be retrieved similarly as an aggregate or by accessing each component separately. In addition, a structured data type is a user-defined data type (UDT) having pieces that can be utilized separately or collectively, depending on the situation.

Simple data types:

  • floating (float, double, long double)
  • integral (char, short, int, long, and bool)
  • enum

Structured data types:

  • class
  • array
  • union
  • struct

Features of an Array

  • An array declaration makes consecutive memory blocks available.
  • Arrays are not dynamic. This means that after an array has been started, it cannot be resized.
  • Each memory block corresponds to a single array element.
  • Array items are identified by a unique number known as the element's subscript/index.
  • Arrays, like variables, must be specified before they may be utilized. To declare an array, use the var keyword.
  • The process of filling the array items is referred to as array initialization.
  • The values of array elements can be edited or modified but not erased.

Advantages of Array

  • Code Optimization: An array aids in code optimization, which improves software speed and performance. It simplifies the process to obtain or sort the array data.
  • Random access: It allows you to access any data in an array in real-time (independent of its position and size). As a result, we can immediately access any data in an array at any index point.

Disadvantages of Array

  • Size Restrictions: An array can only store a certain number of items. We cannot change the size of the array once it has been defined. As a result, inserting more elements than declared is not feasible.

Declaring and Initializing Arrays

First, we'll look over the TypeScript Array Syntax. It was exactly the same as in javascript. But there is one difference, that is we are adding type.

Like Java, it has various methods to create arrays in TypeScript.

Syntax No. 1:

Output:

In the previous example, we defined one variable with the let keyword of type string and then enclosed it in square brackets to indicate that it is of the array type. Then comes the equal (=) symbol, followed by the values in square brackets separated with commas.

Syntax No. 2:

We are now explicitly writing arrays in this type.

Output:

In the previous example, we used the let keyword with the variable name following the colon(:) and declared the data type as an array with the array type being a string.

The only difference between the two examples is the syntax. You may utilize them both at once. There are some standard steps to learn more about. In the following session, we'll look at what it means to initialize arrays.

Initialize an Array in TypeScript

In the above two syntax examples, we can see that both declaration and initialization are done in a single line. Let us spread them and observe how it is truly accomplished.

Syntax No. 1:

Declaring array

Initializing array

Syntax No. 2:

Declaring array

Initializing array

We can define and initialize the array independently or in the same line in a mixed way. It is simply an issue of syntax and programming style that we require.

Access Array Elements

So far, we've learned how to define and initialize an array. Now comes the important part. Of course, in programming, we must do some operations. We need to access array items when doing some action on them. To gain access to these elements, we must first grasp their structure.

We already know that several items may be stored in a single variable. However, those items are recognized by a single unique number that begins with zero (0). These are the index numbers of array elements.

To be more specific, consider the int array with 5 elements.

Now consider the student to be a five-element array.

Let's have a look at the memory structure for accessing the array items.

memory structure of array items

In the figure above, we have index no. We may reach a specific element in an array by using these indexes.

Example:

Output:

Types of Array in Typescript

An array can be of two types:

  1. Single-Dimensional Array
  2. Multi-Dimensional Array

types of array in javascript

Single-Dimensional Array A single-dimensional array is a sort of linear array with only one row for data storage. It just contains one set of square brackets ("[]"). Its elements can be accessed using a row or column index.

Syntax:

Initialization:

Example:

Output:

Multi-Dimensional Array A multi-dimensional array is a collection of one or more arrays. Data is kept in a row and column-based index in the multi-dimensional array (also known as matrix form). A two-dimensional (2-D) array is the most basic type of multi-dimensional array.

2d array example

Syntax:

Initialization

Example:

The above example declares an array with two entries. Each of these items refers to a three-element array. The aforesaid array is illustrated in the diagram below.

array with two entries example

When referring to an array element, the originating array element's subscript must be followed by the referred array element's subscript. The code demonstrates this.

It will create the following JavaScript code after compilation.

Output:

Accessing Array Elements

An array element can be accessed in two ways one by Indexer and another is Loop

Access Array Elements with The Indexer

The indexer is used to access an array element (a single value in the array).

When we make an array, we assign each element a number, which we call its index. If we consider an array to be a table, we would add another row of integers beginning with 0.

index of array example

The index is made up of these integers. When we wish to access a certain element, we provide the compiler with the index number for that element.

It's worth noting that any collection with a number index will always begin at 0, not 1.

Simply place the index number between square brackets after the array name to utilize the indexer.

Example:

Output:

Explanation: In the above example, we access array element number two. Because the index begins at zero, the third element, 'Rupesh,' is sent to the console.

Access Array Elements with A Loop

Although arrays often have multiple values, it makes it more logical to retrieve them within a loop.

We must use a counter as the index to utilize an array within a loop. Let's start with a while loop and then break it down.

Example:

The variable I will serve as the counter. Because arrays begin at zero, we begin by giving the number 0 to the counter.

The counter is then incremented by one in the body of the while loop. This implies that we would begin with the first member of the array, element 0, and proceed through elements 1, 2, 3, and so on as the loop ran.

For an array, the while loop is useful since we can simply increase the counter in the condition. When the loop detects that there are no additional elements in the array, the condition is false and the loop terminates.

In a for loop, we would have to explicitly indicate the number of entries in the array.

Example:

The for loop has the disadvantage of not knowing how many elements are in an array beforehand.

Fortunately, TypeScript has an array.length property that does the math/Calculation for us. To utilize the property, just provide the array name, a dot operator, and the keyword length.

Syntax:

Example:

Output:

Example:

Output:

Since it is guaranteed to loop just the number of times there are items in the loop, the for loop is a safer alternative than the while loop.

Array Object

The TypeScript Array of Objects allows the user to store several values in a single variable at the same time. A fixed-size sequential collection of items of the same type is stored in an array of Objects. Because TypeScript arrays are data types in their own right, just like strings, Booleans, and numbers, we know that there are several methods to declare arrays in TypeScript.

One of them is Array of Objects, which may be defined in TypeScript by inserting brackets after the interface. It might be referred to as an interface or an inline interface. Let's take a deep dive into the TypeScript syntax for declaring an Array of Objects and look at some instances.

Syntax

The syntax for declaring an array of objects using an Inline Type is as follows:

The following is the TypeScript syntax for defining an array of objects using a Named Interface:

So we're utilizing a named interface here.

Implementation Rules and Regulations

  • The majority of the TypeScript Array of Objects may be used interchangeably.
  • Inline Types may be used to alias far more intricate types, and Interfaces are much more prone to fundamental type structure, such as an object or a class, and so on.
  • Since the class does not know which methods or values are to be implemented, users could not use keyword implements on an inline type of union between several types.
  • The user cannot specify an interface extending a union type in the same context. An interface prototype must be given on a declaration, not at the time of use.
  • TypeScript allows combine interface declarations with the same name.
  • Interfaces offer the benefit of combining numerous declarations with the same name, but they are less versatile than union types or advanced inline types.
  • TypeScript uses the Array of Objects Inline Type declaration by default.

An Array of Objects with a Named Interface is a simple example.

Output:

Array Methods

The array has various preset methods that assist us to acquire output quickly.

  • filter(): This method is used to change an existing array and generate a new one. It will apply the new condition to the old values.
  • every(): This function is mostly used for testing. It determines if each entry in an array is true or false.
  • forEach(): Works similarly to the for loop, but on each element of the array.
  • concat(): concretes the array values of two separate arrays and returns a new array, as the name implies.
  • indexOf(): As we've seen, arrays contain index values. This function returns the index of an array element.
  • splice(): We may use this technique to add or delete an array element.
  • sort(): This method implements array element sorting. In the testing scenario, some() returns true if at least one condition is met.
  • unshift(): This function is useful for adding elements to the beginning of an array and returning a new array.
  • function toString(): This function transforms array items to strings and returns them.
  • Shift(): is the inverse of pop in that it removes the first element from an array. It returns the components that were deleted.
  • map(): This method generates a new array. This new array is the result of the condition specified in the map.
  • pop(): retrieves the final element of an array and removes it from the array.
  • reverse(): As the name implies, this function simply reverses the array.
  • reduceRight(): This function applies to the array and decreases the array items from the right. It reduces the provided array to a single value.
  • reduce(): performs the same function as reduceRight. However, in the other direction.
  • lastIndexOf(): Array has no items, as we know. This function returns the array's maximum index value. Nothing but the index number of the array's last value.
  • join(): connects all array items and returns with the provided separator.
  • Push(): If you've ever worked with an array, you're probably familiar with this method. This method adds one or more elements to the array at the end.
  • Slice(): This method can take a piece from an array and return a new array.

Array Destructuring

Destructuring is a javascript feature (EcmaScript 2015), however, Typescript also supports it. You may use this capability to extract data from arrays and objects. However, in this essay, we will concentrate on array destructuring.

The Fundamental Assignment

How does it work with an array? Let's start with a simple exercise.

Output:

When we conduct comparisons, we assign array variables by index, as seen below.

Output:

We can see that destructuring is more appealing and cleaner.

Making Use of Declared Variables

Declared variables can also be destroyed.

Output:

TypeScript Spread Operator

The spread operator's main objective is to distribute the elements of an array or object. The spread operator is in charge of three common tasks:

  • Adding items from one or more arrays to a new array
  • Copying one or more objects' attributes into a new object
  • Spreading an array while invoking a method that accepts just a comma-separated set of inputs

Spreading for arrays and function calls was introduced in ES2015. Spreading for objects was added in ES2018. TypeScript supports both specs.

Spreading arrays and objects, as well as spreading arrays while calling functions, are covered in this section.

Spreading Arrays

When you spread an array, all of its items are duplicated into the new array. If we wish to join several arrays, we may use the spread operator to combine them to make a new array.

In the following example, we have two arrays, firstpersonname and secondpersonname, which we merge to create a new array completecirclenames:

The elements of completecirclenames are determined by the order in which the arrays are dispersed in the array literal. Secondpersonname items will be placed before firstpersonname in the resultant array if we put Secondpersonname before firstpersonname.

It is permissible to spread an empty array, but it has no effect on the output:

So far, we've made it appear like only arrays can be distributed. Spreading is not limited to arrays in reality. An array can contain any iterable object.

An iterable is a JavaScript object that adheres to the iterator protocol, which was introduced in ES2015 as a means for objects to describe iteration behavior in scenarios such as spreading and for..of loops. The iterator protocol is implemented by Array, String, Map, and Set (the constructors for the relevant JavaScript values), thus we may utilize them when spreading to arrays.

Conclusion

  • We've seen what an array contains and how the syntax is constructed to locate the required values in the array.
  • We've also examined some of the TypeScript arrays containing the method's rules and regulations.
  • We've looked at what TypeScript Array of Objects is and how it's utilized in TypeScript.
  • We Described the syntax for declaring an array of objects in two ways: inline typed interfaces and named interfaces.
  • We also looked into the rules for defining an Array of Objects using the Type.
  • In this section, we looked at how we initialize an array in TypeScript. As well as the Typescript Array Methods
  • By utilizing the spread operator, one may copy every item in an array into a new array.