Typescript Array Tutorial with Examples
- Admin
- Mar 6, 2024
- Typescript
Typescript Array: Learn with usage examples.
Array Object in TypeScript
Arrays are fundamental in any programming language, serving as containers for multiple values under a single collection name. In web applications, arrays
are commonly used to store lists of objects, JSON values, custom entries, and primitive values.
In TypeScript, arrays are considered objects or elements, each accessible via an index.
- Arrays Declaration Syntax
Arrays in TypeScript can be declared using various syntaxes. The var
keyword is used along with the variable name and data type.
var variableArrayName[:Data-type];
variableArrayName=[list of objects/elements]
or
var variableArrayName[:Array[Data-type]];
variableArrayName=[list of objects/elements]
Here, variableArrayName is a valid identifier in TypeScript, and DataType represents the type of data in the array.
An array
is a keyword in typescript. datatype
A datatype is a valid primitive or custom type.
How to Declare and Initialize Arrays in TypeScript?
Arrays can be declared and initialized in multiple ways in TypeScript.
One way is to declare a variable with a type and empty square brackets([]
)
var array1: string[];
Then, initialize the array with values. Here, an empty array is assigned with values.
array1 = [];
These two steps can be combined into a single line:
var array1: string[] = [];
Secondly, Arrays can also be declared and initialized using the Array type:
var array2: string[] = new Array();
var array3: string[] = Array();
var array5: Array = new Array();
var array6: Array = Array();
Thirdly, Additionally, arrays can be initialized directly with values:
var array1: string[] = ["one", "two", "three"];
The above array contains values at index 0 (‘one’), index 1 (‘two’), and index 2 (‘three’).
We can also declare an array without a data type, the data type is inferred from assigned data. Compiler assumes from the data type of the array can be decided based on the values of an array.
We will see array examples to check the typeof
of an array, the length of an array, and retrieve an element from an array.
var array1: string[] = ["one", "two", "three"];
console.log(typeof array1); //returns object
console.log(array1.length); //returns 3
console.log(array1[0]); // returns 'one'
console.log(array1[1]); // returns 'two'
console.log(array1[2]); // returns 'three'
console.log(array1[3]); // returns undefined
Let’s see array of example
- to check the type of array
- length of an array
- retrieve an element from the array
How to Declare Arrays of Objects in TypeScript?
In TypeScript, interfaces or classes are commonly used to declare objects. For example, let’s declare a class for an employee:
var emps: string[] = new Array(2);
emps.push("emp1");
emps.push("emp2");
emps.push("emp3");
for (var i = 0; i < emps.length; i++) {
console.log(emps[i]);
}
var newemps: string[] = new Array("test1", "test2"); // accepts parameters separted by comma in Array object Constrcutor
How do declare Arrays of Objects?
In typescript, interfaces or classes are used to declare an object. Let’s declare a class in typescript for employee
interface Employee{
id:number,
name:string
constructor(_id:number, _name:string) {
this.id = _id;
this.name = _name;
}
}
One way, Let’s declare an array of objects with the square bracket syntax
let emps: Employee[] = [];
Another way is, Declare an array with Array syntax
let emps1: Array<Emloyee>;
And also, declare an array using an array with a type of objects in it as seen below
let employees: Array<{ id: number, name: string }>;
finally, declare and initialize an array of objects using single statements
let emps: Employee[] = [new Employee(11, "John"), new Employee(12, "Eric")];
Similarly, initialization can be done by assigning json string objects as seen below
let emps: Employee[] = [
{
id: 11,
name: "John",
},
{
id: 12,
name: "Eric",
},
];
How to Declare Array Strings in TypeScript?
Arrays of strings can be created similarly to arrays of objects, using either empty arrays or the parameter constructor:
var emps: string[] = new Array(2);
emps.push("emp1");
emps.push("emp2");
emps.push("emp3");
for (var i = 0; i < emps.length; i++) {
console.log(emps[i]);
}
var newemps: string[] = new Array("test1", "test2"); // accepts parameters separted by comma in Array object Constrcutor
you can also see typescript array of object declaration
Array Destructuring in TypeScript
Array Destructing, introduced in the latest JavaScript, is also implemented in TypeScript for both objects and arrays. It enhances code readability and reduces size.
Destructing code is more readable and reduces code size. Destructing is separating the elements of an array.
The below examples are to copy two variables without using third variables
var var1 = 5,
var2 = 8;
console.log(var1, var2); // returned 5,8
[var1, var2] = [var2, var1];
console.log(var1, var2); // returned 8,5
In the same way, we can implement it in an array object.
var arrays: number[] = [7, 4, 5];
var [m, n] = arrays;
console.log(m, n); // 7, 4
Generated javascript using transpile is
var arrays = =[7, 4,5];
var x = arrays[0], y = arrays[1];
console.log(m, n); // 7, 4
Array Rest Destructuring in TypeScript
Array rest destructuring, involving the rest operator, is used for extracting multiple elements from an array.
var arrays: number[] = [7, 4, 5, 12];
var [m, n, ...q] = arrays;
console.log(m, n); // 7, 4
console.log(q); // 5,12
We will see the array ignore destructing.
var arrays: number[] = [7, 4, 5, 12];
var [m, , ...q] = arrays;
console.log(m); // 7
console.log(q); // 5,12
Using an empty variable and leaving empty separated by the comma
Array Object Properties length
: returns the count of the elements in the Array Object. Array Object Methods Array Object has different methods provided to manipulate an array of elements.
Method | Description |
---|---|
reverse() | Reverse order of elements in the array. The last element will be the first element, the First element will last element. |
Push() | takes one or more elements as parameters, adds this element to the end of an array, and returns the new length of the array |
pop() | Delete an element from an array from the last position |
concat() | takes one or more elements as parameters, adds this element to an original array, and returns the new array by concat this |
slice() | takes to start and end index, return the part of array elements |
toString() | outputs string form of array object |
shift() | delete the first element from an array index zero elements and returns the first element |
unshift() | takes one more element and these elements at the start of an array ie zero index position, return the completely new array elements |
We will see real use cases of arrays with the example in the following section.
How to remove an element from an array in typescript?
using the splice
method, we can remove the element from an array.
splice(0,1)
- this elements remove the first element and return it.
the first parameter indicates were starting from an array i.e starting element. the second parameter indicates the number of elements to remove. splice(arrays. length,1)
It removes the last element and returns the last element.
How to declare a multidimensional array in typescript?
Multidimensional arrays are used for two-level arrays of mathematical matrix objects. It contains an array of array values.
Arrays contain elements which elements hold arrays. Multidimensional arrays can be declared and initialized as follows.
var dimensions: number[][] = [
[11, 12, 13],
[3, 2, 5],
];
console.log(dimensions[0][0]); // returns 11
console.log(dimensions[0][1]); // returns 12
console.log(dimensions[0][2]); // returns 13
console.log(dimensions[1][0]); // returns 3
console.log(dimensions[1][1]); // returns 2
console.log(dimensions[1][2]); // returns 5
Using Index, we can retrieve elements like a normal array with multiple dimensional indexes.
How to Convert JSON to Array object in typescript
In Applications, We used to get data from REST in the form of a JSON object. From the front end, we need to manipulate JSON objects and display them in the user interface. Converting JSON to arrays is the must-use case that the developer gets to know for efficient programming.
const json = {
Employees: [
{ id: "1", name: "john" },
{ id: "2", name: "Franc" },
{ id: "3", name: "Kiran" },
],
};
const arraysItem = json.Employees.map((emp) => emp.name);
console.log(arraysItem); //return array with three elements -john,Franc,Kiran
How to hold multiple data types values in the array
Usually, arrays hold similar values of the same data type. We can also hold multiple data types like tuple array example.
An example of tuple types
var types1: [number, string] = [11, "cloudhadoop"];
console.log(types1); //return index0 - 11, index1 - cloudhadoop
How to Sort an array in typescript
Arrays.sort(comparator) method is used to sort the elements in an array
let list = ["11", "5", "9"];
console.log(list); // return - return 11,5,9
list.sort((p, q) => p - q);
console.log(list); // Ascending Order - return 5,9,11
let data = [
{ value: "testuser", key: 11 },
{ value: "demo", key: 31 },
{ value: "zoo", key: 2 },
];
Sorting JSON objects based on keys and values and converting to Array:
// sort value in natural ascending order
data.sort((d1, d2) => {
if (d1.value > d2.value) return 1;
if (d1.value < d2.value) return -1;
return 0;
});
console.log(data);
output
{value: "demo", key: 31},
{value: "testuser", key: 11},
{value: "zoo", key: 2},
here is a code for the natural order
// sort key in natural ascending order
data.sort((d1, d2) => {
if (d1.key > d2.key) return 1;
if (d1.key < d2.key) return -1;
return 0;
});
{value: "zoo", key: 2},
{value: "testuser", key: 11},
{value: "demo", key: 31}
How to Iterate/loop elements/objects in a typescript array?
We can use forEach or normal for loop to iterate objects.
In the same logic, we can use a loop object in an array
let list = ["11", "5", "9"];
list.forEach((element) => {
console.log(element);
});
//returns 11,5,9
Conclusion
In summary, this guide provides comprehensive coverage of arrays in TypeScript, accompanied by illustrative examples. Arrays serve as essential data structures in programming, and mastering their usage is fundamental for effective TypeScript development.