TypeScript Array
An array object is used to store a set of values with a single variable name.
Arrays are very common.
If you have a set of data (e.g., website names) stored in individual variables as shown below:
var site1 = "Google";
var site2 = "tutorialpro";
var site3 = "Taobao";
This becomes impractical if you have 10, 100, or more such variables. In such cases, we can use arrays to solve the problem:
var sites: string[];
sites = ["Google", "tutorialpro", "Taobao"];
This looks much cleaner.
The syntax for declaring an array in TypeScript is as follows:
var array_name[: datatype]; // declaration
array_name = [val1, val2, valn..] // initialization
Or you can initialize the array directly during declaration:
var array_name[: datatype] = [val1, val2…valn]
If the array is declared without a type, it is considered to be of type any
, and the type is inferred from the first element during initialization.
Example
Create an array of type number
:
var numlist: number[] = [2, 4, 6, 8];
The entire array structure is as follows:
The first index is 0. We can access array elements using their index:
TypeScript
var sites: string[];
sites = ["Google", "tutorialpro", "Taobao"];
console.log(sites[0]);
console.log(sites[1]);
Compiling the above code produces the following JavaScript code:
JavaScript
var sites;
sites = ["Google", "tutorialpro", "Taobao"];
console.log(sites[0]);
console.log(sites[1]);
The output is:
Google
tutorialpro
In the following example, we initialize the array directly during declaration:
TypeScript
var nums: number[] = [1, 2, 3, 4];
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
Compiling the above code produces the following JavaScript code:
JavaScript
var nums = [1, 2, 3, 4];
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
The output is:
1
2
3
4
Array Object
We can also create arrays using the Array object.
The Array constructor accepts the following values:
- A number representing the array size.
- A list of initial elements separated by commas.
Example
Specify the initial size of the array:
TypeScript
var arr_names: number[] = new Array(4);
for (var i = 0; i < arr_names.length; i++) {
arr_names[i] = i * 2;
console.log(arr_names[i]);
}
Compiling the above code produces the following JavaScript code:
JavaScript
var arr_names = new Array(4);
for (var i = 0; i < arr_names.length; i++) {
arr_names[i] = i * 2;
console.log(arr_names[i]);
}
The output is:
0
2
4
6
In the following example, we initialize the array elements directly:
TypeScript
var sites: string[] = new Array("Google", "tutorialpro", "Taobao", "Facebook");
for (var i = 0; i < sites.length; i++) {
console.log(sites[i]);
}
Compiling the above code produces the following JavaScript code:
JavaScript
var sites = new Array("Google", "tutorialpro", "Taobao", "Facebook");
for (var i = 0; i < sites.length; i++) {
console.log(sites[i]);
}
The output is:
Google
tutorialpro
Taobao
Facebook
Array Destructuring
We can also assign array elements to variables, as shown below:
TypeScript
var arr: number[] = [12, 13];
var [x, y] = arr; // Assigns array elements to variables x and y
console.log(x);
console.log(y);
Compiling the above code produces the following JavaScript code:
JavaScript
var arr = [12, 13];
var x = arr[0], y = arr[1]; // Assigns array elements to variables x and y
console.log(x);
console.log(y);
The output is:
12
13
Array Iteration
We can use a for
loop to iterate over the elements of an array:
TypeScript
var j: any;
var nums: number[] = [1001, 1002, 1003, 1004];
for (j in nums) {
console.log(nums[j]);
}
Compiling the above code produces the following JavaScript code:
JavaScript
var j;
var nums = [1001, 1002, 1003, 1004];
for (j in nums) {
console.log(nums[j]);
}
The output is:
1001
1002
1003
1004
Multidimensional Arrays
An array can contain another array, forming a multidimensional array.
The simplest form of a multidimensional array is a two-dimensional array, defined as follows:
var arr_name: datatype[][] = [[val1, val2, val3], [v1, v2, v3]];
Example
Define a two-dimensional array with three elements in each dimension:
TypeScript
var multi: number[][] = [[1, 2, 3], [23, 24, 25]];
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);
Compiling the above code produces the following JavaScript code:
JavaScript
var multi = [[1, 2, 3], [23, 24, 25]];
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);
The output is:
1
2
3
23
24
25
Using Arrays in Functions
Passing Arrays to Functions
TypeScript
var sites: string[] = new Array("Google", "tutorialpro", "Taobao", "Facebook");
function disp(arr_sites: string[]) {
for (var i = 0; i < arr_sites.length; i++) {
console.log(arr_sites[i]);
}
}
disp(sites);
Compiling the above code produces the following JavaScript code:
JavaScript
var sites = new Array("Google", "tutorialpro", "Taobao", "Facebook");
function disp(arr_sites) {
for (var i = 0; i < arr_sites.length; i++) {
console.log(arr_sites[i]);
}
}
disp(sites);
The output is:
Google
tutorialpro
Taobao
Facebook
Returning Arrays from Functions
TypeScript
function disp(): string[] {
return new Array("Google", "tutorialpro", "Taobao", "Facebook");
}
var sites: string[] = disp();
for (var i in sites) {
console.log(sites[i]);
}
Compiling the above code produces the following JavaScript code:
JavaScript
function disp() {
return new Array("Google", "tutorialpro", "Taobao", "Facebook");
}
var sites = disp();
for (var i in sites) {
console.log(sites[i]);
}
The output is:
Google
tutorialpro
Taobao
Facebook
Array Methods
The following table lists some commonly used array methods:
No. | Method & Description | Example |
---|---|---|
1. | concat() Joins two or more arrays and returns the result. | var alpha = ["a", "b", "c"]; <br>var numeric = [1, 2, 3];<br>var alphaNumeric = alpha.concat(numeric); <br>console.log("alphaNumeric : " + alphaNumeric ); // a,b,c,1,2,3 |
2. | every() Checks if every element in an array passes the test. | function isBigEnough(element, index, array) { <br> return (element >= 10); <br>} <br><br>var passed = [12, 5, 8, 130, 44].every(isBigEnough); <br>console.log("Test Value : " + passed ); // false |
3. | filter() checks array elements and returns an array of all elements that meet the condition. | function isBigEnough(element, index, array) { <br> return (element >= 10); <br>} <br> <br>var passed = [12, 5, 8, 130, 44].filter(isBigEnough); <br>console.log("Test Value : " + passed ); // 12,130,44 |
4. | forEach() executes a provided function once for each array element. | let num = [7, 8, 9];<br>num.forEach(function (value) {<br> console.log(value);<br>}); Compiled to JavaScript code: var num = [7, 8, 9];<br>num.forEach(function (value) {<br> console.log(value); // 7 8 9<br>}); |
5. | indexOf() searches for an element in the array and returns its position. If not found, it returns -1, indicating no such item. | var index = [12, 5, 8, 130, 44].indexOf(8); <br>console.log("index is : " + index ); // 2 |
6. | join() joins all elements of an array into a string. | var arr = new Array("Google","tutorialpro","Taobao"); <br> <br>var str = arr.join(); <br>console.log("str : " + str ); // Google,tutorialpro,Taobao<br> <br>var str = arr.join(", "); <br>console.log("str : " + str ); // Google, tutorialpro, Taobao<br> <br>var str = arr.join(" + "); <br>console.log("str : " + str ); // Google + tutorialpro + Taobao |
7. | lastIndexOf() returns the last occurrence of a specified string value, searching backward from a specified position in the string. | var index = [12, 5, 8, 130, 44].lastIndexOf(8); <br>console.log("index is : " + index ); // 2 |
8. | map() processes each element in the array through a specified function and returns the processed array. | var numbers = [1, 4, 9]; <br>var roots = numbers.map(Math.sqrt); <br>console.log("roots is : " + roots ); // 1,2,3 |
9. | pop() removes the last element from an array and returns that element. | var numbers = [1, 4, 9]; <br> <br>var element = numbers.pop(); <br>console.log("element is : " + element ); // 9<br> <br>var element = numbers.pop(); <br>console.log("element is : " + element ); // 4 |
10. | push() adds one or more elements to the end of an array and returns the new length. | var numbers = new Array(1, 4, 9); <br>var length = numbers.push(10); <br>console.log("new numbers is : " + numbers ); // 1,4,9,10 <br>length = numbers.push(20); <br>console.log("new numbers is : " + numbers ); // 1,4,9,10,20 |
11. | reduce() computes array elements into a single value from left to right. | var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); <br>console.log("total is : " + total ); // 6 |
12. | reduceRight() computes array elements into a single value from right to left. | var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; }); <br>console.log("total is : " + total ); // 6 |
13. | reverse() reverses the order of elements in an array. | var arr = [0, 1, 2, 3].reverse(); <br>console.log("Reversed array is : " + arr ); // 3,2,1,0 |
14. | shift() removes and returns the first element of the array. | var arr = [10, 1, 2, 3].shift(); <br>console.log("Shifted value is : " + arr ); // 10 |
15. | slice() selects a part of an array and returns a new array. | var arr = ["orange", "mango", "banana", "sugar", "tea"]; <br>console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); // mango<br>console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) ); // mango,banana |
16. | some() checks if any array elements pass the test implemented by the provided function. | function isBigEnough(element, index, array) { <br> return (element >= 10); <br> <br>} <br> <br>var retval = [2, 5, 8, 1, 4].some(isBigEnough);<br>console.log("Returned value is : " + retval ); // false<br> <br>var retval = [12, 5, 8, 1, 4].some(isBigEnough); <br>console.log("Returned value is : " + retval ); // true |
17. | sort() sorts the elements of an array. | var arr = new Array("orange", "mango", "banana", "sugar"); <br>var sorted = arr.sort(); <br>console.log("Returned string is : " + sorted ); // banana,mango,orange,sugar |
18. | splice() adds or removes elements from an array. | var arr = ["orange", "mango", "banana", "sugar", "tea"]; <br>var removed = arr.splice(2, 0, "water"); <br>console.log("After adding 1: " + arr ); // orange,mango,water,banana,sugar,tea <br>console.log("removed is: " + removed); <br> <br>removed = arr.splice(3, 1); <br>console.log("After removing 1: " + arr ); // orange,mango,water,sugar,tea <br>console.log("removed is: " + removed); // banana |
19. | toString() converts an array to a string and returns the result. | var arr = new Array("orange", "mango", "banana", "sugar"); <br>var str = arr.toString(); <br>console.log("Returned string is : " + str ); // orange,mango,banana,sugar |
20. | unshift() adds one or more elements to the beginning of an array and returns the new length. | var arr = new Array("orange", "mango", "banana", "sugar"); <br>var length = arr.unshift("water"); <br>console.log("Returned array is : " + arr ); // water,orange,mango,banana,sugar <br>console.log("Length of the array is : " + length ); // 5 |