Array Declaration
The array declaration in typescript can be made in two ways:
1. Using Generic Array type
var array_name: Array<elementType> = [v1,v2,..]
Example:
var Location: Array<string> = ['Delhi', 'Mumbai', 'Kolkata'];
2. Using Square Bracket
var array_name:[datatype] = [v1,v2,..]
Example:
var Location: string[] = ['Delhi', 'Mumbai', 'Kolkata'];
Accessing Elements in Typescript Array
1) We can access the array element using ArrayName[index].
Access Array Element
Var location: string[] = ['Delhi', 'Mumbai', 'Bangalore', 'Pune'];
Output:
location[0]; // returns Delhi
location[3]; // returns Pune
location[2]; // returns Bangalore
location[1]; // returns Mumbai
2) We can also access the array element using the FOR loop
Var location: string[] = ['Delhi', 'Mumbai', 'Punjab'];
for (var index in location) {
console.log(location[index]); // output: Delhi Mumbai Punjab
}
for (var i = 0; i < location.length; i++) {
console.log(location[i]); // output: Delhi Mumbai Punjab
}
Types of Array in TypeScript
There are two types of array:
- Single-Dimensional(1-D) Array
- Multi-Dimensional (2-D,3-D,..) Array
Single-Dimensional(1-D) Array
A single-dimensional array is a linear type array, which has only one row for storing data. A single set of the square bracket ("[ ]")is used.
Syntax:
Var array_name[:datatype];
Example:
Var arr: number[];
arr = [9, 8, 7, 6]
console.log("Array[0]: " + arr[0]);
console.log("Array[1]: " + arr[1]);
Output:
Array[0]: 1
Array[1]: 2
Multi-Dimensional (2-D) Array
A Multi-dimensional array is stored in rows and columns of a matrix, where the first index signifies the row and the second index shows the column. The first element( a[0][0] ) is at (row 0) and at (column 0) index.
Syntax:
Var arr_name:datatype[][] = [ [a1,a2,a3], [b1,b2,b3] ];
Example:
var myArr:number[][] = [[1,2,3],[5,6,7]] ;
console.log(myArr[0][0]);
console.log(myArr[0][1]);
console.log(myArr[0][2]);
console.log(myArr[1][0]);
console.log(myArr[1][1]);
console.log(myArr[1][2]);
Output:
1
2
3
4
5
6
Some Key Points of Array in TypeScript
- An array, once initialized, cannot be resized (Arrays are static).
- Element values of an Array can be modified but cannot be deleted.
- Arrays should be declared before they are used ( Ex- var, let ).
- Array elements are characterized by a unique integer called the index of the element.
- Array index represents the address of the starting element.
Array in TypeScript Methods
concat()
This method creates a new array by concatenating the existing arrays.
<script>
const names = ["Delhi", "Mumbai"];
const place = [“london”, “England”];
const location = names.concat(place);
</script>
Output:
["Delhi", "Mumbai", “london”, “England”];
pop()
This method removes the last element in the array and returns that element.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.pop();
</script>
Output:
["Delhi", "Mumbai", "Bihar"];
shift()
This method removes the first element (index[0] )of an array .
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.shift();
</script>
Output:
["Mumbai", "Bihar", "Punjab"];
push()
This method adds a new element to the end of the array returns the length of the new array.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.push(“Nepal”);
</script>
Output:
["Delhi", "Mumbai", "Bihar", "Punjab", “Nepal”];
unshift()
This Method adds new elements to the beginning of an array.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.unshift(“Jammu”);
</script>
Output:
[“Jammu”, "Delhi", "Mumbai", "Bihar", "Punjab", “Nepal”];
splice()
This method is used to change the content of an array, adding new elements while removing old elements.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.splice(0, 1);
</script>
Output:
["Mumbai", "Bihar", "Punjab"];
slice()
This method slices out a piece of an array and returns the new array.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.slice(1,3);
</script>
Output:
["Mumbai", "Bihar"];
toString()
This method returns out an array as a comma-separated string.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.toString();
</script>
Output:
Delhi,Mumbai,Bihar,Punjab
join()
This method joins all the elements of the array into strings.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.join(“*”);
</script>
Output:
Delhi*Mumbai*Bihar*Punjab
reverse()
This method is used to reverse the order of the elements in an array.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.reverse();
</script>
Output:
["Punjab","Bihar","Mumbai","Delhi"];
fill()
This method Fills specified elements in an array with a value.
<script>
const names = ["Delhi", "Mumbai", "Bihar", "Punjab"];
names.fill(“New”);
</script>
Output:
[New,New,New,New];
indexOf()
This method returns the first index of an array at which a given element can be found in the array and -1 if it is unavailable.
<script>
const Location =["Delhi", "Mumbai", "Bihar", "Punjab"];
let index = Location.IndexOf("Mumbai");
</script>
Output:
1
lastindexOf()
This method returns the last index of an array at which a given element can be found in the array and -1 if it is unavailable.
<script>
const Location =["Delhi", "Mumbai", "Bihar", "Punjab"];
let index = Location.lastIndexOf("Delhi");
</script>
Output:
2
reduce()
This method applies from left-to-right to a function simultaneously against two array values to crop down it to a single value.
<script>
const numbers = [175, 50, 25];
var store = numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
</script>
Output:
100
every()
This method checks whether all elements in the array pass the test implemented by the function.
<script>
const check = (currentValue) {
currentValue < 40;
}
const array1 = [1, 30, 39, 19, 10, 13];
console.log(array1.every(check));
</script>
Output:
true
some()
This method tests whether the element in the array passes the test condition used by the provided function.
<script>
function isBig(element, index, array) {
return (element >= 10);
}
var arr = [3, 2, 8, 1, 4];
Var value= arr.some(isBig);
console.log("Returned value is : " + value);
</script>
Output:
Returned value is : false
Advantages of Array
- TypeScript arrays offer type safety, ensuring that elements are of the specified data type.
- Arrays support modern JavaScript features like map, filter, reduce, and forEach.
- TypeScript provides built-in methods and syntax for working with arrays, enhancing developer productivity.
- Arrays in TypeScript seamlessly integrate with other language features like interfaces and generics.
Disadvantages of Array
- TypeScript arrays are still subject to some of the limitations of JavaScript arrays, such as fixed size and inefficient insertion/deletion.
- Handling asynchronous operations with arrays in TypeScript might require additional complexity, especially when dealing with Promises or async/await.
- TypeScript arrays may introduce overhead in terms of type checking and compilation time, particularly in large codebases.
- TypeScript arrays do not inherently provide immutability or structural sharing, which can impact performance and memory usage in certain scenarios.
Frequently Asked Questions
How to Take Array Input in TypeScript?
To take array input in TypeScript, you can use various methods like prompting the user, reading from a file, or receiving input from a web form. You can then parse the input and store it in an array variable.
How to Write Array of Strings in TypeScript?
In TypeScript, you can declare an array of strings by specifying the data type followed by square brackets. For example:
let names: string[] = ["John", "Alice", "Bob"];
What is Array Type in Object in TypeScript?
In TypeScript, an array type in an object represents an array containing elements of a specific data type. For example:
let person: { name: string, hobbies: string[] } = {
name: "John",
hobbies: ["reading", "hiking", "cooking"]
};
Here, hobbies is an array containing strings.
Conclusion
In this blog, we discussed arrays in TypeScript and their features, their declaration, how to access them, and different methods. We also saw that using an array, we can randomly access the data present inside it using the location pointer.
If you are pursuing a new career in Web Development, we suggest you get your fundamentals crystal clear with our Full Stack Development course.
This course will help you!