Typescript Array Tutorial with Examples
- Admin
- Oct 3, 2023
- Typescript
Typescript Array: Learn with usage examples.
Array Object in Typescript
Arrays are the basics of any language, used to store multiple values under one collection name.
Basically, in a web application, we will use Arrays
for storing a list of objects,
a list of JSON values, and custom entries as well as for storing primitive values.
In typescripts arrays are objects or elements. Each Element from arrays can be retrieved by index.
Typescript arrays syntax declaration
Arrays in typescript can be declared with different syntax
The var
keyword is used to declare with variable name and datatype
.
A datatype is a valid primitive or custom type. The variable name is a valid identifier in typescript.
var variableArrayName[:Data-type];
variableArrayName=[list of objects/elements]
or
var variableArrayName[:Array[Data-type]];
variableArrayName=[list of objects/elements]
variablename
is a valid identifier in typescript
An array
is a keyword in typescript.
datatype
is a data type of data in an array
How do declare and initialize arrays in Typescript?
We can declare arrays and initialize them in many ways
One way, declares a variable with type and empty square bracket syntax([])
var array1: string[];
After that, initialize an array with the square brackets of values. Here, an empty array is assigned with values.
array1 = [];
Both the above lines can be replaced with single-line syntax
var array1: string[] = [];
Secondly, arrays can be declared and initialized with the Array
type
var array2: string[] = new Array();
var array3: string[] = Array();
var array5: Array = new Array();
var array6: Array = Array();
Thirdly, You can also declare and initialize an array using a single line using literal syntax as seen below
var array1: string[] = ["one", "two", "three"];
The above array holds values at index 0 - ‘one’, index 1- ‘two’, 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
Arrays Object Constructor example
It is another way of creating Arrays using the constructor with an optional initial size.
Following below create Array Object using empty arrays or 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
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 do declare Arrays Strings in Typescript?
We can also create Array Object using empty arrays or 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 Destructing in typescript
Array Destructing feature is introduced in the latest javascript. Typescript is also implemented in the object as well as arrays. 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
We will see the array destructing with rest operator.
The above example has an array with three elements, assigned two variables, copied two values from an array to two variables, third will be ignored.
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 a summary, you learned arrays in typescript with examples.